esbuild-wasm-bundler/mod.ts

70 lines
2.0 KiB
TypeScript
Raw Normal View History

2024-06-07 16:54:12 -04:00
import * as ESBuildWASM from "https://deno.land/x/esbuild@v0.21.4/wasm.js";
import * as Mapper from "https://esm.sh/esbuild-plugin-importmaps@1.0.0"; // https://github.com/andstellar/esbuild-plugin-importmaps | https://github.com/jspm/import-map
import { ImportMap, type IImportMap } from "https://esm.sh/@jspm/import-map";
export const Root = new URL(`file://${Deno.cwd().replaceAll("\\", "/")}`).toString();
function importmapPlugin(importmap:IImportMap):ESBuildWASM.Plugin {
const map = new ImportMap({
map: importmap,
});
return {
name: "importmap-url",
setup(build) {
build.onResolve({ filter: /^[^.].*$/ }, (args) => {
let path;
try
{
path = map.resolve(args.path, args.importer);
console.log("resolved path:", path);
return { path, namespace: "importmap-url" };
}
catch(e)
{
console.log("e r r o r:", args);
return { path: args.importer };
}
});
build.onLoad(
{ filter: /.*/, namespace: "importmap-url" },
async (args) => {
const response = await fetch(args.path);
const contents = await response.text();
const ext = args.path.split(".").pop();
const loader = /** @type {import('esbuild').Loader} */ (
ext?.match(/"j|tsx?$/) ? ext : "js"
);
console.log("loaded", args);
return { contents, loader } as ESBuildWASM.OnLoadResult;
},
);
},
};
}
export default async(importMap:IImportMap, buildOptions?:ESBuildWASM.BuildOptions)=>
{
await ESBuildWASM.initialize({ worker: false });
const result = await ESBuildWASM.build({
entryPoints: ["entry"],
bundle: true,
minify: true,
format: "esm",
outfile:"bundle.js",
entryNames: `[dir][name]`,
jsx: "automatic",
jsxImportSource: "react",
...buildOptions,
plugins:[
...buildOptions?.plugins??[],
importmapPlugin(importMap) as ESBuildWASM.Plugin
]
});
ESBuildWASM.stop();
return result;
};