esbuild-wasm-bundler/serve.tsx
2024-06-10 22:51:23 -04:00

55 lines
1.7 KiB
TypeScript

import bundler from "./mod.ts";
import {Root} from "./introspect.ts"
const transpiled:Map<string, string> = new Map();
const ServeJS =(inText:string)=> new Response(inText, {headers:{"content-type":"application/javascript"}});
const htmlFile = Deno.readTextFileSync(Deno.cwd()+"/index.html");
Deno.serve(async(req)=>{
const url = new URL(req.url);
const index = url.pathname.lastIndexOf(".");
if(index > -1)
{
const ext = url.pathname.substring(index+1);
if(ext === "ts" || ext == "tsx" || ext == "js" || ext == "jsx")
{
if(ext == "js")
{
const lookup = transpiled.get(url.pathname);
if(lookup)
{
return ServeJS(lookup);
}
}
else
{
const lookup = transpiled.get(url.pathname.substring(0, index)+".js");
if(lookup)
{
return ServeJS(lookup);
}
}
try
{
const results = await bundler({
entryPoints:["."+url.pathname],
outdir:"/",
entryNames: `[dir][name]`,
splitting: true
});
results.outputFiles?.forEach(output=>{
transpiled.set(output.path, output.text);
})
return ServeJS(results.outputFiles[0].text);
}
catch(e)
{
return new Response("404", {status:404});
}
}
}
return new Response(htmlFile, {headers:{"content-type": "text/html"}});
});