-
Notifications
You must be signed in to change notification settings - Fork 237
/
build-assets.mjs
executable file
·121 lines (115 loc) · 3.09 KB
/
build-assets.mjs
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
#!/usr/bin/env node
import * as esbuild from 'esbuild'
import {
lessLoader
}
from 'esbuild-plugin-less';
import {
writeFile,
opendir,
unlink
}
from 'node:fs/promises';
import path from 'node:path';
import parseArgs from 'minimist';
const config = {
entryPoints: [
'root/static/js/main.mjs',
'root/static/less/style.less',
],
assetNames: '[name]-[hash]',
entryNames: '[name]-[hash]',
format: 'esm',
outdir: 'root/assets',
bundle: true,
sourcemap: true,
inject: ['root/static/js/inject.mjs'],
loader: {
'.eot': 'file',
'.svg': 'file',
'.ttf': 'file',
'.woff': 'file',
'.woff2': 'file',
},
plugins: [
lessLoader(),
new class {
name = 'metacpan-build';
setup(build) {
build.onResolve({
filter: /^\//
},
() => ({
external: true
}),
);
build.initialOptions.metafile = true;
build.onStart(() => {
console.log('building assets...')
});
build.onEnd(async result => {
const outputs = result?.metafile?.outputs;
if (outputs) {
const files = Object.keys(outputs).sort()
.map(file => path.relative(build.initialOptions.outdir, file));
try {
await writeFile(
path.join(build.initialOptions.outdir, 'assets.json'),
JSON.stringify(files),
'utf8',
);
}
catch (e) {
console.log(e);
}
console.log(`build complete (${files.filter(f => !f.match(/\.map$/)).join(' ')})`);
}
});
}
},
],
};
const args = parseArgs(process.argv, {
boolean: [
'watch',
'minify',
'clean',
],
});
if (args.minify) {
config.minify = true;
}
if (args.clean) {
for await (const file of await opendir(config.outdir, {
withFileTypes: true
})) {
const filePath = path.join(file.parentPath, file.name);
if (file.name.match(/^\./)) {
// ignore these
}
else if (!file.isFile()) {
console.log(`cowardly refusing to remove non-file ${filePath}`);
}
else {
console.log(`deleting ${filePath}`);
await unlink(filePath);
}
}
}
const ctx = await esbuild.context(config);
if (args.watch) {
await ctx.watch();
const sig = await new Promise(resolve => {
[
'SIGTERM',
'SIGQUIT',
'SIGINT',
].map(sig => process.on(sig, resolve));
});
process.stderr.write(`Caught signal: ${sig}\n`);
ctx.dispose();
}
else {
await ctx.rebuild();
ctx.dispose();
}