-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathESBuildOptimizer.js
More file actions
55 lines (48 loc) · 1.55 KB
/
Copy pathESBuildOptimizer.js
File metadata and controls
55 lines (48 loc) · 1.55 KB
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
// @flow
import {transform} from 'esbuild';
import {Optimizer} from '@parcel/plugin';
import {blobToString, normalizePath} from '@parcel/utils';
import SourceMap from '@parcel/source-map';
import path from 'path';
import invariant from 'assert';
export default (new Optimizer({
async optimize({contents, map, bundle, options, getSourceMapReference}) {
if (!bundle.env.shouldOptimize) {
return {contents, map};
}
let relativeBundlePath = path.relative(
options.projectRoot,
path.join(bundle.target.distDir, bundle.name),
);
let code = await blobToString(contents);
if (map) {
let vlqMappings = await map.stringify({
file: normalizePath(relativeBundlePath + '.map'),
format: 'inline',
});
// Flow things...
invariant(typeof vlqMappings === 'string');
code += `\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,${vlqMappings}`;
}
let {code: js, map: jsSourceMap} = await transform(code, {
sourcemap: 'external',
sourcefile: relativeBundlePath,
minify: true,
treeShaking: true,
});
let sourcemap = null;
if (jsSourceMap) {
sourcemap = new SourceMap(options.projectRoot);
let parsedMap = JSON.parse(jsSourceMap);
sourcemap.addVLQMap(parsedMap);
let sourcemapReference = await getSourceMapReference(sourcemap);
if (sourcemapReference) {
js += `\n//# sourceMappingURL=${sourcemapReference}\n`;
}
}
return {
contents: js,
map: sourcemap || map,
};
},
}): Optimizer);