forked from stenciljs/core
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathterser.ts
62 lines (50 loc) · 1.5 KB
/
terser.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
51
52
53
54
55
56
57
58
59
60
61
62
import fs from 'fs-extra';
import { join } from 'path';
import { rollup } from 'rollup';
import type { BuildOptions } from '../../utils/options';
/**
* Creates a bundle containing Terser
* @param opts the options being used during a build
* @returns a tuple containing the bundled Terser code and the path where it
* was written
*/
export async function bundleTerser(opts: BuildOptions): Promise<[content: string, path: string]> {
if (!opts.terserVersion) {
throw new Error('Terser version not set on build opts!');
}
const fileName = `terser-${opts.terserVersion.replace(/\./g, '_')}-bundle-cache${opts.isProd ? '.min' : ''}.js`;
const cacheFile = join(opts.scriptsBuildDir, fileName);
try {
const content = await fs.readFile(cacheFile, 'utf8');
return [content, cacheFile];
} catch (e) {}
const rollupBuild = await rollup({
input: join(opts.nodeModulesDir, 'terser', 'main.js'),
external: ['source-map'],
});
const { output } = await rollupBuild.generate({
format: 'es',
strict: false,
});
let code = output[0].code;
const { minify } = await import('terser');
if (opts.isProd) {
const minified = await minify(code, {
ecma: 2018,
compress: {
ecma: 2018,
passes: 2,
},
format: {
ecma: 2018,
comments: false,
},
});
if (minified.code) {
code = minified.code;
}
}
code = `// Terser ${opts.terserVersion}\n` + code;
await fs.writeFile(cacheFile, code);
return [code, cacheFile];
}