|
| 1 | +import { build, context } from 'esbuild'; |
| 2 | +import { mkdir, rm, writeFile } from 'node:fs/promises'; |
| 3 | +import { resolve } from 'node:path'; |
| 4 | + |
| 5 | +const watch = process.argv.includes('--watch'); |
| 6 | + |
| 7 | +const outdir = resolve('dist/assets/js'); |
| 8 | + |
| 9 | +async function prepareOutDir() { |
| 10 | + await rm(outdir, { recursive: true, force: true }); |
| 11 | + await mkdir(outdir, { recursive: true }); |
| 12 | +} |
| 13 | + |
| 14 | +const baseConfig = { |
| 15 | + entryPoints: ['src/js/graph.ts', 'src/js/search.ts', 'src/js/analytics.ts'], |
| 16 | + outdir, |
| 17 | + bundle: true, |
| 18 | + sourcemap: true, |
| 19 | + format: 'esm', |
| 20 | + target: ['es2022'], |
| 21 | + splitting: true, |
| 22 | + chunkNames: 'chunks/[name]-[hash]', |
| 23 | + metafile: true, |
| 24 | + loader: { |
| 25 | + '.json': 'json', |
| 26 | + }, |
| 27 | + define: { |
| 28 | + 'process.env.NODE_ENV': JSON.stringify(watch ? 'development' : 'production'), |
| 29 | + }, |
| 30 | + minify: !watch, |
| 31 | +}; |
| 32 | + |
| 33 | +async function writeMetaFile(metafile) { |
| 34 | + const metaPath = resolve(outdir, 'meta.json'); |
| 35 | + await writeFile(metaPath, JSON.stringify(metafile, null, 2), 'utf-8'); |
| 36 | +} |
| 37 | + |
| 38 | +async function runBuild() { |
| 39 | + await prepareOutDir(); |
| 40 | + |
| 41 | + if (watch) { |
| 42 | + const ctx = await context(baseConfig); |
| 43 | + await ctx.watch(); |
| 44 | + console.log('🔁 esbuild is watching for changes'); |
| 45 | + } else { |
| 46 | + const result = await build({ |
| 47 | + entryPoints: ['src/js/graph.ts', 'src/js/search.ts', 'src/js/analytics.ts', 'src/js/glitch.ts'], |
| 48 | + outdir, |
| 49 | + bundle: true, |
| 50 | + sourcemap: true, |
| 51 | + format: 'esm', |
| 52 | + target: ['es2022'], |
| 53 | + splitting: true, |
| 54 | + chunkNames: 'chunks/[name]-[hash]', |
| 55 | + metafile: true, |
| 56 | + loader: { |
| 57 | + '.json': 'json', |
| 58 | + }, |
| 59 | + define: { |
| 60 | + 'process.env.NODE_ENV': JSON.stringify(watch ? 'development' : 'production'), |
| 61 | + }, |
| 62 | + minify: !watch, |
| 63 | + }); |
| 64 | + await writeMetaFile(result.metafile); |
| 65 | + console.log('✅ esbuild build complete'); |
| 66 | + } |
| 67 | +} |
| 68 | + |
| 69 | +runBuild().catch((error) => { |
| 70 | + console.error(error); |
| 71 | + process.exit(1); |
| 72 | +}); |
| 73 | + |
0 commit comments