-
Notifications
You must be signed in to change notification settings - Fork 14
/
build.js
75 lines (71 loc) · 1.96 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
// @ts-check
import esbuild from 'esbuild';
import fs from 'fs';
import path, { dirname } from 'path';
import { fileURLToPath } from 'url';
import { buildItems } from './build-items.js';
let __dirname = dirname(fileURLToPath(import.meta.url));
let packageRootPath = __dirname;
function jsBanner() {
let license = fs.readFileSync(path.join(packageRootPath, './LICENSE')).toString();
return (
'/**\n' +
' * @license\n' +
license
.split('\n')
.map((line) => ` * ${line}`)
.join('\n') +
'\n */'
);
}
/** @param {import('./build-items.js').BuildItem} buildItem */
function build(buildItem) {
esbuild
.build({
entryPoints: [buildItem.in],
format: buildItem.iife ? 'iife' : 'esm',
globalName: buildItem.iife ? 'UC' : undefined,
keepNames: buildItem.iife ? true : undefined,
bundle: true,
minify: buildItem.minify,
sourcemap: false,
outfile: buildItem.out,
target: 'es2019',
banner: {
js: jsBanner(),
},
})
.then(async () => {
if (!buildItem.minifyHtml) {
return;
}
let js = fs.readFileSync(buildItem.out).toString();
/** @param {string} str */
let checkIfHtml = (str) => {
return str.includes('<') && (str.includes('</') || str.includes('/>'));
};
/** @param {string} ch */
let processChunk = (ch) => {
if (checkIfHtml(ch)) {
let htmlMin = ch.split('\n').join(' ');
while (htmlMin.includes(' ')) {
htmlMin = htmlMin.split(' ').join(' ');
}
htmlMin = htmlMin.split('> <').join('><');
return htmlMin.trim();
}
return ch;
};
let result = js
.split('`')
.map((chunk) => processChunk(chunk))
.join('`')
.split(`'`)
.map((chunk) => processChunk(chunk))
.join(`'`);
fs.writeFileSync(buildItem.out, result);
});
}
for (let buildItem of buildItems) {
build(buildItem);
}