diff --git a/src/dev/esbuild.ts b/src/dev/esbuild.ts index b587b610..aeb77d1f 100644 --- a/src/dev/esbuild.ts +++ b/src/dev/esbuild.ts @@ -19,7 +19,7 @@ export interface BuildOutput { files: Array<{ hash: string | null; contents: Uint8Array; path: string }>; } -let esbuild: null | typeof import("esbuild-wasm") = null; +let esbuild: null | typeof import("esbuild") = null; const PREACT_ENV = Deno.env.get("PREACT_PATH"); @@ -27,11 +27,7 @@ export async function bundleJs( options: FreshBundleOptions, ): Promise { if (esbuild === null) { - esbuild = Deno.env.get("FRESH_ESBUILD_LOADER") === "portable" - ? await import("esbuild-wasm") - : await import("esbuild"); - - await esbuild.initialize({}); + await startEsbuild(); } try { @@ -42,7 +38,7 @@ export async function bundleJs( } } - const bundle = await esbuild.build({ + const bundle = await esbuild!.build({ entryPoints: options.entryPoints, platform: "browser", @@ -117,7 +113,21 @@ export async function bundleJs( } if (!options.dev) { - await esbuild.stop(); + // deno-lint-ignore no-deprecated-deno-api + const children = Object.values(Deno.resources()) + .filter((name) => name === "child").length; + await esbuild!.stop(); + // To work around a bug in ESBuild, where it doesn't wait for the child + // process to shut down before exiting, we manually wait for the process to + // exit before continuing. + while ( + // deno-lint-ignore no-deprecated-deno-api + Object.values(Deno.resources()) + .filter((name) => name === "child").length >= children + ) { + await new Promise((r) => setTimeout(r, 100)); + } + esbuild = null; } return { @@ -127,6 +137,14 @@ export async function bundleJs( }; } +export async function startEsbuild() { + esbuild = Deno.env.get("FRESH_ESBUILD_LOADER") === "portable" + ? await import("esbuild-wasm") + : await import("esbuild"); + + await esbuild.initialize({}); +} + function buildIdPlugin(buildId: string): EsbuildPlugin { return { name: "fresh-build-id",