/
terser.ts
69 lines (59 loc) 路 1.84 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
63
64
65
66
67
68
69
import { minify } from "../deps/terser.ts";
import { merge } from "../core/utils.ts";
import { Exception } from "../core/errors.ts";
import { Page } from "../core/filesystem.ts";
import { prepareAsset, saveAsset } from "./source_maps.ts";
import type { DeepPartial, Helper, Site } from "../core.ts";
import type { MinifyOptions } from "../deps/terser.ts";
export interface Options {
/** The list of extensions this plugin applies to */
extensions: string[];
/** Options passed to `terser` */
options: MinifyOptions;
}
// Default options
export const defaults: Options = {
extensions: [".js"],
options: {
module: true,
compress: true,
mangle: true,
},
};
/** A plugin to load all JavaScript files and minify them using Terser */
export default function (userOptions?: DeepPartial<Options>) {
const options = merge(defaults, userOptions);
return (site: Site) => {
site.loadAssets(options.extensions);
site.process(options.extensions, terser);
site.filter("terser", filter as Helper, true);
async function terser(page: Page) {
const { content, filename, sourceMap, enableSourceMap } = prepareAsset(
site,
page,
);
const terserOptions = {
...options.options,
sourceMap: enableSourceMap
? {
content: JSON.stringify(sourceMap),
filename: filename,
}
: undefined,
};
try {
const output = await minify({ [filename]: content }, terserOptions);
saveAsset(site, page, output.code!, output.map);
} catch (cause) {
throw new Exception(
"Error processing the file",
{ name: "Plugin Terser", cause, page, content },
);
}
}
async function filter(code: string) {
const output = await minify(code, options.options);
return output.code;
}
};
}