|
| 1 | +import * as esbuild from "esbuild"; |
| 2 | +import { denoPlugins } from "@luca/esbuild-deno-loader"; |
| 3 | +import { debounce } from "@std/async/debounce"; |
| 4 | +import { ResolvedConfig } from "./interface.ts"; |
| 5 | + |
| 6 | +export class Builder extends EventTarget { |
| 7 | + constructor(public manifest: ResolvedConfig) { |
| 8 | + super(); |
| 9 | + } |
| 10 | + |
| 11 | + async watch(watchRoot: string, debounceTimeout: number = 200) { |
| 12 | + const fn = debounce(this.build.bind(this), debounceTimeout); |
| 13 | + const watcher = Deno.watchFs(watchRoot); |
| 14 | + for await (const _ of watcher) { |
| 15 | + await fn(); |
| 16 | + } |
| 17 | + } |
| 18 | + |
| 19 | + async build() { |
| 20 | + console.log("Building..."); |
| 21 | + |
| 22 | + const config: Partial<Parameters<typeof esbuild.build>[0]> = { |
| 23 | + define: resolveDefines(this.manifest), |
| 24 | + sourcemap: this.manifest.esbuild.sourcemap, |
| 25 | + minify: this.manifest.esbuild.minify, |
| 26 | + plugins: [...denoPlugins()], |
| 27 | + platform: "browser", |
| 28 | + entryPoints: [this.manifest.entry], |
| 29 | + outfile: this.manifest.out, |
| 30 | + external: this.manifest.esbuild.external, |
| 31 | + bundle: true, |
| 32 | + format: "esm", |
| 33 | + // Explicitly compile decorators, as this what Jumble->Vite |
| 34 | + // does, and no browsers currently support (any form of) decorators, |
| 35 | + // and if we're bundling, we're probably running in a browser. |
| 36 | + tsconfigRaw: { |
| 37 | + compilerOptions: { |
| 38 | + experimentalDecorators: true, |
| 39 | + }, |
| 40 | + }, |
| 41 | + }; |
| 42 | + |
| 43 | + if (this.manifest.esbuild.metafile) { |
| 44 | + config.metafile = true; |
| 45 | + } |
| 46 | + |
| 47 | + const result = await esbuild.build(config); |
| 48 | + esbuild.stop(); |
| 49 | + |
| 50 | + if (this.manifest.esbuild.metafile && result.metafile) { |
| 51 | + await Deno.writeTextFile( |
| 52 | + this.manifest.esbuild.metafile, |
| 53 | + JSON.stringify(result.metafile), |
| 54 | + ); |
| 55 | + |
| 56 | + console.log(await esbuild.analyzeMetafile(result.metafile)); |
| 57 | + } |
| 58 | + this.dispatchEvent(new CustomEvent("build")); |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +function resolveDefines( |
| 63 | + manifest: ResolvedConfig, |
| 64 | +): Record<string, string> { |
| 65 | + return Object.keys(manifest.esbuild.define).reduce((defines, envName) => { |
| 66 | + const value = manifest.esbuild.define[envName]; |
| 67 | + defines[envName] = typeof value === "string" ? `"${value}"` : `undefined`; |
| 68 | + return defines; |
| 69 | + }, {} as Record<string, string>); |
| 70 | +} |
0 commit comments