/
build.js
71 lines (61 loc) · 1.54 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
import esbuild from 'esbuild';
import env from 'env-smart';
import { resolve } from 'node:path';
import { copyFile } from 'node:fs/promises';
// load .env file
env.load();
const PORT = 8081;
const DEV = process.argv.includes('--dev');
const API_URL = process.env.API_URL;
const OUTFILE = resolve('dist/app.js');
const ENTRY = resolve('src/index.js');
/** @type {import('servbot').ServbotServer?} **/
let server;
/** @type {esbuild.BuildOptions} **/
const esbuildConfig = {
format: 'iife',
entryPoints: [ENTRY],
outfile: OUTFILE,
bundle: true,
minify: !DEV,
sourcemap: DEV,
jsxFactory: 'm',
jsxFragment: '"["',
define: {
'process.env.API_URL': `"${API_URL}"`,
'window.DEV_MODE': DEV ? 'true' : 'false'
},
plugins: [{
name: 'on-end',
setup(build) {
build.onEnd(({ errors }) => {
if (errors[0]) {
console.error('Bundling Failed!', errors[0]);
return;
}
console.log('Bundled: ', OUTFILE);
if (server) server.reload();
});
}
}]
};
// create & configure context
const ctx = await esbuild.context(esbuildConfig);
if (DEV) {
const servbot = await import('servbot');
server = servbot.default({
root: 'dist',
reload: true,
fallback: 'index.html'
});
server.listen(PORT);
await ctx.watch();
process.on('exit', () => {
ctx.dispose();
server.close();
});
} else {
// copy index.html -> 200.html fallback for surge.sh SPA support
await copyFile(resolve('dist/index.html'), resolve('dist/200.html'));
ctx.rebuild().finally(ctx.dispose);
}