-
Notifications
You must be signed in to change notification settings - Fork 28
/
minifyWorker.ts
50 lines (43 loc) · 1.17 KB
/
minifyWorker.ts
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
/**
* Copyright © Magento, Inc. All rights reserved.
* See COPYING.txt for license details.
*/
import terser, { MinifyOptions, SourceMapOptions } from 'terser';
type StringMinificationResult = {
code: string;
map: string;
};
// The RequireJS runtime, in some cases
// relies on Function.prototype.toString
// to find calls to `require`. These must
// be preserved
const mangleOptions = {
reserved: ['require'],
};
/**
* @summary Minifies JS code, optionally chaining from
* a provided source-map
*/
export async function minifyFromString(
code: string,
filename: string,
map?: string,
): Promise<StringMinificationResult> {
const opts: MinifyOptions = {
sourceMap: {
filename,
url: `${filename}.map`,
},
mangle: mangleOptions,
};
if (map) {
try {
const parsedMap = JSON.parse(map) as SourceMapOptions['content'];
// @ts-ignore
opts.sourceMap.content = parsedMap;
} catch {}
}
const result = terser.minify(code, opts);
if (result.error) throw result.error;
return { code: result.code as string, map: result.map as string };
}