Log in
scripts/build.js 41 lines · 1.4 KB · javascript
1
// Build the static site into dist/. With --serve, also serve it on
2
// http://localhost:3000 (localhost counts as a secure context for WebSerial).
3
4
import { cp, mkdir, rm } from 'node:fs/promises';
5
import { join } from 'node:path';
6
7
const root = join(import.meta.dir, '..');
8
const dist = join(root, 'dist');
9
10
await rm(dist, { recursive: true, force: true });
11
await mkdir(dist, { recursive: true });
12
13
const result = await Bun.build({
14
  entrypoints: [join(root, 'web/app.js')],
15
  outdir: dist,
16
  target: 'browser',
17
  minify: true,
18
  sourcemap: 'linked',
19
});
20
if (!result.success) {
21
  for (const message of result.logs) console.error(message);
22
  process.exit(1);
23
}
24
await cp(join(root, 'web/index.html'), join(dist, 'index.html'));
25
await cp(join(root, 'web/style.css'), join(dist, 'style.css'));
26
27
const size = result.outputs.filter((o) => o.kind === 'entry-point').reduce((n, o) => n + o.size, 0);
28
console.log(`Built dist/ (app.js ${(size / 1024).toFixed(1)} KB)`);
29
30
if (process.argv.includes('--serve')) {
31
  const server = Bun.serve({
32
    port: 3000,
33
    async fetch(req) {
34
      let path = new URL(req.url).pathname;
35
      if (path.endsWith('/')) path += 'index.html';
36
      const file = Bun.file(join(dist, path));
37
      return (await file.exists()) ? new Response(file) : new Response('Not found', { status: 404 });
38
    },
39
  });
40
  console.log(`Serving on http://localhost:${server.port}`);
41
}