esbuild-wasm-bundler/mod.ts

83 lines
2.3 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
export const Root = new URL(`file://${Deno.cwd().replaceAll("\\", "/")}`).toString()+"/";
console.log("running at", Root);
type Resolver = Parameters<ESBuild.PluginBuild["onResolve"]>[1];
const prefix = "/_dot_importer_/";
const Resolver:Resolver =(args)=>
{
console.log("RESOLVE");
console.log("in:", 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",
}
console.log("out:", output);
return output;
}
const FetchTSX =async(inPath:string):Promise<ESBuild.OnLoadResult>=>
{
console.log("fetching", inPath);
const result = await fetch(inPath);
const contents = await result.text();
return { contents, loader: `tsx` };
}
const resolvePlugin:ESBuild.Plugin = {
name: "resolve-plugin",
setup(build) {
build.onResolve({ filter: /^\.\/.*$/ }, Resolver);
build.onResolve({ filter: /^(\.\.\/).*$/ }, Resolver);
build.onLoad({ filter: /.*/, namespace:"http" }, async(args)=> {
console.log("LOAD WEB");
console.log("in:", args);
const fetchPath = args.path.substring(prefix.length);
console.log("fetching", fetchPath);
const result = await fetch(fetchPath);
const contents = await result.text();
return { contents, loader: `tsx` };
});
},
};
type ImportMap = Parameters<typeof Mapper.importmapPlugin>[0];
await ESBuild.initialize({ worker: false });
const result = await ESBuild.build({
//entryPoints: ["./app.tsx"],
entryPoints: ["./deep/deep.tsx"],
//entryPoints: ["http://localhost:4507/deep/deep.tsx"],
bundle: true,
minify: true,
format: "esm",
jsx: "automatic",
jsxImportSource: "react",
plugins:[
resolvePlugin,
Mapper.importmapPlugin({
imports:{
"react":"https://esm.sh/preact@10.22.0/compat"
}
}) as ESBuild.Plugin
]
});
ESBuild.stop();
for(const item of result.outputFiles)
{
//console.log(item.text)
}