UNPKG

2.85 kBJavaScriptView Raw
1var _path = require("path");
2var _fs = require("fs");
3var _terser = (obj = require("terser")) && obj.__esModule ? obj : {
4 default: obj
5};
6var obj;
7var _time = require("dr-js/library/common/time");
8var _format = require("dr-js/library/common/format");
9var _main = require("./main");
10exports.getTerserOption = (({isDevelopment = !1, isModule = !1}) => {
11 return {
12 ecma: 8,
13 toplevel: !0,
14 parse: {
15 ecma: 8
16 },
17 compress: {
18 ecma: 8,
19 toplevel: !0,
20 join_vars: !1,
21 sequences: !1,
22 global_defs: {
23 "process.env.NODE_ENV": isDevelopment ? "development" : "production",
24 __DEV__: Boolean(isDevelopment)
25 }
26 },
27 mangle: !isModule && {
28 toplevel: !0
29 },
30 output: isModule ? {
31 ecma: 8,
32 beautify: !0,
33 indent_level: 2,
34 width: 240
35 } : {
36 ecma: 8,
37 beautify: !1,
38 semicolons: !1
39 },
40 sourceMap: !1
41 };
42});
43const minifyWithTerser = ({filePath, option, logger}) => {
44 const timeStart = (0, _time.clock)();
45 const scriptSource = (0, _fs.readFileSync)(filePath, {
46 encoding: "utf8"
47 });
48 const {error, code: scriptOutput} = _terser.default.minify(scriptSource, option);
49 if (error) {
50 logger.padLog(`[minifyWithTerser] failed to minify file: ${filePath}`);
51 throw error;
52 }
53 (0, _fs.writeFileSync)(filePath, scriptOutput);
54 const timeEnd = (0, _time.clock)();
55 return {
56 sizeSource: Buffer.byteLength(scriptSource),
57 sizeOutput: Buffer.byteLength(scriptOutput),
58 timeStart,
59 timeEnd
60 };
61};
62exports.minifyWithTerser = minifyWithTerser;
63exports.minifyFileListWithTerser = (async ({fileList, option, rootPath = "", logger}) => {
64 logger.padLog(`minify ${fileList.length} file with terser`);
65 const table = [];
66 let totalTimeStart = (0, _time.clock)();
67 let totalSizeSource = 0;
68 let totalSizeDelta = 0;
69 for (const filePath of fileList) {
70 const {sizeSource, sizeOutput, timeStart, timeEnd} = minifyWithTerser({
71 filePath,
72 option,
73 logger
74 });
75 const sizeDelta = sizeOutput - sizeSource;
76 totalSizeSource += sizeSource;
77 totalSizeDelta += sizeDelta;
78 _main.__VERBOSE__ && table.push([ `∆ ${(100 * sizeDelta / sizeSource).toFixed(2)}% (${(0, _format.binary)(sizeDelta)}B)`, (0, _format.time)(timeEnd - timeStart), `${(0, _path.relative)(rootPath, filePath)}` ]);
79 }
80 _main.__VERBOSE__ && table.push([ "--", "--", "--" ]);
81 table.push([ `∆ ${(100 * totalSizeDelta / totalSizeSource).toFixed(2)}% (${(0, _format.binary)(totalSizeDelta)}B)`, (0, _format.time)((0, _time.clock)() - totalTimeStart), `TOTAL of ${fileList.length} file (${(0, _format.binary)(totalSizeSource)}B)` ]);
82 logger.log(`result:\n ${(0, _format.padTable)({
83 table,
84 padFuncList: [ "L", "R", "L" ],
85 cellPad: " | ",
86 rowPad: "\n "
87 })}`);
88 return totalSizeDelta;
89});
\No newline at end of file