-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
SwcOptimizer.js
77 lines (68 loc) 路 2.02 KB
/
SwcOptimizer.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
// @flow
import nullthrows from 'nullthrows';
import {minify} from '@swc/core';
import {Optimizer} from '@parcel/plugin';
import {blobToString} from '@parcel/utils';
import SourceMap from '@parcel/source-map';
import path from 'path';
export default (new Optimizer({
async loadConfig({config, options}) {
let userConfig = await config.getConfigFrom(
path.join(options.projectRoot, 'index'),
['.terserrc', '.terserrc.js', '.terserrc.cjs'],
);
if (userConfig) {
let isJavascript = path.extname(userConfig.filePath) === '.js';
if (isJavascript) {
config.invalidateOnStartup();
}
}
return userConfig?.contents;
},
async optimize({
contents,
map: originalMap,
bundle,
config: userConfig,
options,
getSourceMapReference,
}) {
if (!bundle.env.shouldOptimize) {
return {contents, map: originalMap};
}
let code = await blobToString(contents);
let config = {
mangle: true,
compress: true,
...userConfig,
sourceMap: bundle.env.sourceMap
? {
filename: path.relative(
options.projectRoot,
path.join(bundle.target.distDir, bundle.name),
),
}
: false,
toplevel:
bundle.env.outputFormat === 'esmodule' ||
bundle.env.outputFormat === 'commonjs',
module: bundle.env.outputFormat === 'esmodule',
};
let result = await minify(code, config);
let sourceMap = null;
let minifiedContents: string = nullthrows(result.code);
let resultMap = result.map;
if (resultMap) {
sourceMap = new SourceMap(options.projectRoot);
sourceMap.addVLQMap(JSON.parse(resultMap));
if (originalMap) {
sourceMap.extends(originalMap);
}
let sourcemapReference = await getSourceMapReference(sourceMap);
if (sourcemapReference) {
minifiedContents += `\n//# sourceMappingURL=${sourcemapReference}\n`;
}
}
return {contents: minifiedContents, map: sourceMap};
},
}): Optimizer);