-
Notifications
You must be signed in to change notification settings - Fork 0
/
build.js
149 lines (134 loc) · 4.5 KB
/
build.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
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
const esbuild = require("esbuild");
const terser = require("terser");
const tsc = require("tsc-prog");
const fs = require("fs");
const zlib = require("zlib");
function convertToUMD(text, globalName) {
// HACK: convert to UMD - only supports cjs and global var
const varName = "__EXPORTS__";
let code = text;
code = code.replace(/export\s*\{([^{}]+)\}/, (_, inner) => {
const defaultExport = inner.match(/^(\w+) as default$/);
return defaultExport != null
? `var ${varName}=${defaultExport[1]}`
: `var ${varName}={${inner.replace(/(\w+) as (\w+)/g, "$2:$1")}}`;
});
code = `(()=>{${code};typeof module!=='undefined'?module.exports=${varName}:self.${globalName}=${varName}})()`;
return code;
}
async function build({
globalName,
entryPoint,
outfileName,
clean = false,
minify = true,
external = []
}) {
try {
let rootdir = entryPoint.split("/").slice(0, -1).join("/");
let outdir = outfileName.split("/").slice(0, -1).join("/");
let tscProgOptions2 = {
basePath: __dirname, // always required, used for relative paths
configFilePath: "tsconfig.json", // config to inherit from (optional)
files: [entryPoint],
pretty: true,
copyOtherToOutDir: false,
clean: clean ? [outdir] : [],
skipLibCheck: true,
compilerOptions: {
rootDir: rootdir,
declaration: true,
outDir: outdir,
emitDeclarationOnly: true
},
bundleDeclaration: {
entryPoint: "index.d.ts" // relative to the OUTPUT directory ('dist' here)
}
};
tsc.build(tscProgOptions2);
let cjs = esbuild.buildSync({
entryPoints: [entryPoint],
bundle: true,
sourcemap: "external",
write: false,
minify: false,
outdir: outdir,
target: "esnext",
loader: { ".js": "jsx", ".ts": "tsx", ".mjs": "jsx" },
format: "cjs",
metafile: true,
external
});
let esm = esbuild.buildSync({
entryPoints: [entryPoint],
bundle: true,
sourcemap: "external",
write: false,
minify: false,
outdir: outdir,
target: "esnext",
loader: { ".js": "jsx", ".ts": "tsx", ".mjs": "jsx" },
format: "esm",
metafile: true,
external
});
let esmContent = esm.outputFiles[1].text;
// HACK: simulate __dirname and __filename for esm
if (esmContent.indexOf("__dirname") || esmContent.indexOf("__filename")) {
esmContent =
`import { fileURLToPath } from 'url';\nconst __filename = fileURLToPath(import.meta.url);\nconst __dirname = path.dirname(__filename);\n` +
esmContent;
if (esmContent.indexOf("import path from") === -1) {
esmContent = `import path from 'path';\n` + esmContent;
}
}
fs.writeFileSync(`${outfileName}.mjs`, esmContent);
fs.writeFileSync(`${outfileName}.js`, cjs.outputFiles[1].text);
let text = await esbuild.analyzeMetafile(esm.metafile, { verbose: true });
console.log(text);
let result2;
if (minify) {
let code = convertToUMD(esm.outputFiles[1].text, globalName);
result2 = await terser.minify(code, {
sourceMap: {
content: esm.outputFiles[0].text.toString()
},
compress: {
booleans_as_integers: false
},
output: {
wrap_func_args: false
},
ecma: 2020
});
let mapBase64 = Buffer.from(result2.map.toString()).toString("base64");
let map = `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${mapBase64}`;
fs.writeFileSync(`${outfileName}.min.js`, result2.code);
fs.writeFileSync(`${outfileName}.min.js.map`, map);
}
function formatBytesToKiloBytes(bytes) {
return (bytes / 1024).toFixed(2) + "kb";
}
let header = `/*** ${entryPoint} ***/`;
console.log(header);
console.log("Esm", formatBytesToKiloBytes(esm.outputFiles[1].text.length));
if (minify) {
console.log("Minified:", formatBytesToKiloBytes(result2.code.length));
// Get the size using gzip compression
const gzip = zlib.gzipSync(result2.code);
console.log("Gzip:", formatBytesToKiloBytes(gzip.length));
// Get the size using brotli algorithm
const brotli = zlib.brotliCompressSync(result2.code);
console.log("Brotli:", formatBytesToKiloBytes(brotli.length));
}
console.log(`/${Array(header.length).fill("*").join("")}/`);
} catch (e) {
console.error(e);
}
}
build({
globalName: "Benchmark",
entryPoint: "./lib/index.ts",
outfileName: "./dist/index",
clean: true
});