esbuild-wasm-bundler/mod.ts
2024-06-10 22:51:23 -04:00

65 lines
1.9 KiB
TypeScript

import * as ESBuild from "https://deno.land/x/esbuild@v0.19.2/wasm.js";
import * as Mapper from "https://esm.sh/esbuild-plugin-importmaps@1.0.0"; // https://github.com/andstellar/esbuild-plugin-importmaps
import Introspect, {Root} from "./introspect.ts";
const prefix = "/_dot_importer_/";
const resolvePlugin:ESBuild.Plugin = {
name: "resolve-plugin",
setup(build) {
build.onResolve({ filter: /^(\.\/|\.\.\/).*/ }, (args)=>
{
let resolveRoot = args.importer||Root;
if(resolveRoot.startsWith(prefix))
{
resolveRoot = resolveRoot.substring(prefix.length);
}
const output:ESBuild.OnResolveResult = {
path:prefix + new URL(args.path, resolveRoot).href,
namespace:"http",
}
return output;
});
build.onLoad({ filter: /.*/, namespace:"http" }, async(args)=> {
const fetchPath = args.path.substring(prefix.length);
const result = await fetch(fetchPath);
const contents = await result.text();
return { contents, loader: `tsx` };
});
},
};
await ESBuild.initialize({ worker: false });
export type ImportMap = Parameters<typeof Mapper.importmapPlugin>[0];
export type BuildOptions = ESBuild.BuildOptions;
export default async function(buildOptions={} as BuildOptions, importMap:ImportMap|false = false)
{
if(importMap === false)
{
importMap = await Introspect() as ImportMap;
}
const configuration:ESBuild.BuildOptions = {
//entryPoints: ["./app.tsx"],
entryPoints: ["entry"],
//entryPoints: ["./deep/deep.tsx"],
//entryPoints: ["http://localhost:4507/deep/deep.tsx"],
bundle: true,
minify: true,
format: "esm",
jsx: "automatic",
jsxImportSource: "react",
...buildOptions,
plugins: [
resolvePlugin,
Mapper.importmapPlugin(importMap) as ESBuild.Plugin,
...buildOptions.plugins||[]
]
};
const result = await ESBuild.build(configuration);
//ESBuild.stop();
return result;
}
export { ESBuild };