| 1 |
import chokidar from "chokidar"; |
| 2 |
import { context } from "esbuild"; |
| 3 |
import svelte from "esbuild-svelte"; |
| 4 |
import { typescript } from "svelte-preprocess-esbuild"; |
| 5 |
|
| 6 |
import { compilerOptions } from "./tsconfig.json"; |
| 7 |
|
| 8 |
/** |
| 9 |
* Create a debounced function. |
| 10 |
*/ |
| 11 |
function debounce(func: () => void, wait: number): () => void { |
| 12 |
let timeout: NodeJS.Timeout | null = null; |
| 13 |
return () => { |
| 14 |
if (timeout) { |
| 15 |
clearTimeout(timeout); |
| 16 |
} |
| 17 |
timeout = setTimeout(() => { |
| 18 |
timeout = null; |
| 19 |
func(); |
| 20 |
}, wait); |
| 21 |
}; |
| 22 |
} |
| 23 |
|
| 24 |
/** |
| 25 |
* Build the frontend using esbuild. |
| 26 |
* @param dev - Whether to generate sourcemaps and watch for changes. |
| 27 |
*/ |
| 28 |
async function runBuild(dev: boolean) { |
| 29 |
const ctx = await context({ |
| 30 |
entryPoints: ["src/main.ts"], |
| 31 |
format: "esm", |
| 32 |
bundle: true, |
| 33 |
outfile: "../src/fava/static/app.js", |
| 34 |
conditions: dev ? ["development"] : ["production"], |
| 35 |
external: ["module"], // for web-tree-sitter |
| 36 |
loader: { |
| 37 |
".wasm": "file", |
| 38 |
".woff": "empty", |
| 39 |
".woff2": "file", |
| 40 |
}, |
| 41 |
plugins: [ |
| 42 |
svelte({ |
| 43 |
compilerOptions: { dev }, |
| 44 |
preprocess: typescript(), |
| 45 |
}), |
| 46 |
], |
| 47 |
sourcemap: dev, |
| 48 |
target: compilerOptions.target, |
| 49 |
}); |
| 50 |
console.log("starting build"); |
| 51 |
await ctx.rebuild(); |
| 52 |
console.log("finished build"); |
| 53 |
|
| 54 |
if (!dev) { |
| 55 |
await ctx.dispose(); |
| 56 |
} else { |
| 57 |
console.log("watching for file changes"); |
| 58 |
const rebuild = debounce(() => { |
| 59 |
console.log("starting rebuild"); |
| 60 |
ctx.rebuild().then( |
| 61 |
() => { |
| 62 |
console.log("finished rebuild"); |
| 63 |
}, |
| 64 |
(err: unknown) => { |
| 65 |
console.error(err); |
| 66 |
}, |
| 67 |
); |
| 68 |
}, 200); |
| 69 |
chokidar |
| 70 |
.watch(["src", "css"], { |
| 71 |
awaitWriteFinish: true, |
| 72 |
ignoreInitial: true, |
| 73 |
}) |
| 74 |
.on("all", (eventName: string, path: string) => { |
| 75 |
console.log(`${path} ${eventName}`); |
| 76 |
rebuild(); |
| 77 |
}); |
| 78 |
} |
| 79 |
} |
| 80 |
|
| 81 |
if (require.main === module) { |
| 82 |
const dev = process.argv.includes("--watch"); |
| 83 |
runBuild(dev).catch((e: unknown) => { |
| 84 |
console.error(e); |
| 85 |
}); |
| 86 |
} |