forked from TrySound/rollup-plugin-terser
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathrollup-plugin-terser.js
122 lines (106 loc) · 3.02 KB
/
rollup-plugin-terser.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
const {
codeFrameColumns
} = require("@babel/code-frame");
const {
Worker
} = require("jest-worker");
const serialize = require("serialize-javascript");
function terser(userOptions = {}) {
if (userOptions.sourceMap != null) {
throw Error(
"sourceMap option is removed. Now it is inferred from rollup options."
);
}
if (userOptions.sourcemap != null) {
throw Error(
"sourcemap option is removed. Now it is inferred from rollup options."
);
}
return {
name: "terser",
async renderChunk(code, chunk, outputOptions) {
if (!this.worker) {
this.worker = new Worker(require.resolve("./transform.js"), {
numWorkers: userOptions.numWorkers,
});
this.numOfBundles = 0;
}
this.numOfBundles++;
const defaultOptions = {
sourceMap: outputOptions.sourcemap === true ||
typeof outputOptions.sourcemap === "string",
};
if (outputOptions.format === "es" || outputOptions.format === "esm") {
defaultOptions.module = true;
}
if (outputOptions.format === "cjs") {
defaultOptions.toplevel = true;
}
const normalizedOptions = {
...defaultOptions,
...userOptions
};
// remove plugin specific options
for (let key of ["numWorkers"]) {
if (normalizedOptions.hasOwnProperty(key)) {
delete normalizedOptions[key];
}
}
const serializedOptions = serialize(normalizedOptions);
try {
const result = await this.worker.transform(code, serializedOptions);
if (result.nameCache) {
let {
vars,
props
} = userOptions.nameCache;
// only assign nameCache.vars if it was provided, and if terser produced values:
if (vars) {
const newVars =
result.nameCache.vars && result.nameCache.vars.props;
if (newVars) {
vars.props = vars.props || {};
Object.assign(vars.props, newVars);
}
}
// support populating an empty nameCache object:
if (!props) {
props = userOptions.nameCache.props = {};
}
// merge updated props into original nameCache object:
const newProps =
result.nameCache.props && result.nameCache.props.props;
if (newProps) {
props.props = props.props || {};
Object.assign(props.props, newProps);
}
}
return result.result;
} catch (error) {
const {
message,
line,
col: column
} = error;
console.error(
codeFrameColumns(code, {
start: {
line,
column
}
}, {
message
})
);
throw error;
} finally {
this.numOfBundles--;
if (this.numOfBundles === 0) {
this.worker.end();
this.worker = 0;
}
}
},
};
}
exports.terser = terser;