/
postprocess.js
119 lines (109 loc) · 3.14 KB
/
postprocess.js
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
// @ts-check
import * as esbuild from "esbuild";
import * as UglifyJS from "uglify-js";
import * as EOL2 from "elm-optimize-level-2"
/**
* @type {import("elm-watch/elm-watch-node").Postprocess}
*/
export default async function postprocess({
code,
targetName,
compilationMode,
}) {
switch (compilationMode) {
case "standard":
case "debug":
return code;
case "optimize":
return EOL2.transform(code, true) // o3Enabled
.then(optimized =>
minify(optimized, {
// `minimal: true` runs both UglifyJS and esbuild, which results in smaller output but is slow.
// `minimal: false` runs only esbuild, which is super fast but results in slightly larger output.
// This enables the `minimal` mode for _some_ targets, based on their names in elm-watch.json,
// as an example. For some apps, faster builds is more important than smaller output, and vice versa.
// Make your choice.
minimal: !["Html", "Sandbox", "Element", "Document", "Worker"].includes(
targetName
),
})
);
default:
throw new Error(
`Unknown compilation mode: ${JSON.stringify(compilationMode)}`
);
}
}
const pureFuncs = [
"F2",
"F3",
"F4",
"F5",
"F6",
"F7",
"F8",
"F9",
"A2",
"A3",
"A4",
"A5",
"A6",
"A7",
"A8",
"A9",
];
// Source: https://discourse.elm-lang.org/t/what-i-ve-learned-about-minifying-elm-code/7632
async function minify(code, { minimal }) {
return minimal ? runUglifyJSAndEsbuild(code) : runEsbuild(code);
}
async function runUglifyJSAndEsbuild(code) {
const result = UglifyJS.minify(code, {
compress: {
...Object.fromEntries(
Object.entries(UglifyJS.default_options().compress).map(
([key, value]) => [key, value === true ? false : value]
)
),
pure_funcs: pureFuncs,
pure_getters: true,
strings: true,
sequences: true,
merge_vars: true,
switches: true,
dead_code: true,
if_return: true,
inline: true,
join_vars: true,
reduce_vars: true,
conditionals: true,
collapse_vars: true,
unused: true,
},
mangle: false,
});
if (result.error !== undefined) {
throw result.error;
}
return (
await esbuild.transform(result.code, {
minify: true,
target: "es5",
})
).code;
}
async function runEsbuild(code) {
return (
await esbuild.transform(removeIIFE(code), {
minify: true,
pure: pureFuncs,
target: "es5",
format: "iife",
})
).code;
}
function removeIIFE(code) {
return `var scope = window;${code.slice(
code.indexOf("{") + 1,
code.lastIndexOf("}")
)}`;
}