-
Notifications
You must be signed in to change notification settings - Fork 24.4k
/
Copy pathindex.js
82 lines (70 loc) · 2.08 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
/**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
'use strict';
const constantFolding = require('./constant-folding');
const extractDependencies = require('./extract-dependencies');
const inline = require('./inline');
const minify = require('./minify');
function makeTransformParams(filename, sourceCode, options) {
if (filename.endsWith('.json')) {
sourceCode = 'module.exports=' + sourceCode;
}
return {filename, sourceCode, options};
}
function transformCode(transform, filename, sourceCode, options, callback) {
const params = makeTransformParams(filename, sourceCode, options.transform);
const isJson = filename.endsWith('.json');
transform(params, (error, transformed) => {
if (error) {
callback(error);
return;
}
var code, map;
if (options.minify) {
const optimized =
constantFolding(filename, inline(filename, transformed, options));
code = optimized.code;
map = optimized.map;
} else {
code = transformed.code;
map = transformed.map;
}
if (isJson) {
code = code.replace(/^\w+\.exports=/, '');
} else {
// Remove shebang
code = code.replace(/^#!.*/, '');
}
const result = isJson || options.extern
? {dependencies: [], dependencyOffsets: []}
: extractDependencies(code);
result.code = code;
result.map = map;
callback(null, result);
});
}
exports.transformAndExtractDependencies = (
transform,
filename,
sourceCode,
options,
callback
) => {
transformCode(require(transform), filename, sourceCode, options || {}, callback);
};
exports.minify = (filename, code, sourceMap, callback) => {
var result;
try {
result = minify(filename, code, sourceMap);
} catch (error) {
callback(error);
}
callback(null, result);
};
exports.transformCode = transformCode; // for easier testing