-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathminify.js
More file actions
77 lines (66 loc) · 1.91 KB
/
minify.js
File metadata and controls
77 lines (66 loc) · 1.91 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
// @ts-check
import * as fs from "node:fs";
import * as zlib from "node:zlib";
/**
* @typedef {{
time: number,
size: number,
brotliSize: number
}} Stats
*
* @typedef {(code: string, inputFile: string) => string | Promise<string>} RunMinifier
*/
class KnownError extends Error {}
/**
* @param {RunMinifier} runMinifier
*/
export async function minify(runMinifier) {
minifyHelper(runMinifier).catch((error) => {
console.error(error instanceof KnownError ? error.message : error);
process.exitCode = 1;
});
}
/**
* @param {RunMinifier} runMinifier
*/
export async function minifyHelper(runMinifier) {
const [, , inputFile, outputFile, noSideEffects = "false", ...restArgs] =
process.argv;
if (inputFile === undefined) {
throw new KnownError(
`Expected the input .js file to minify as the first argument.`,
);
}
if (outputFile === undefined) {
throw new KnownError(
`Expected the output .js file to put the minified code into as the second argument.`,
);
}
if (restArgs.length > 0) {
throw new KnownError(
`Expected two or three arguments, but got ${restArgs.length} extra: ${JSON.stringify(restArgs)}`,
);
}
const rawCode = fs.readFileSync(inputFile, "utf8");
const code =
noSideEffects === "true" ? addNoSideEffectsComments(rawCode) : rawCode;
const start = Date.now();
const minified = await runMinifier(code, inputFile);
const elapsed = Date.now() - start;
/** @type {Stats} */
const stats = {
time: elapsed,
size: Buffer.byteLength(minified),
brotliSize: zlib.brotliCompressSync(minified).byteLength,
};
fs.writeFileSync(outputFile, minified);
fs.writeFileSync(`${outputFile}.json`, JSON.stringify(stats, null, 2) + "\n");
}
/**
*
* @param {string} code
* @returns {string}
*/
function addNoSideEffectsComments(code) {
return code.replace(/^function [FA]\d\(/gm, "/* @__NO_SIDE_EFFECTS__ */ $&");
}