esbuild-wasm-bundler/serve.tsx

55 lines
1.7 KiB
TypeScript
Raw Normal View History

2024-06-07 16:54:12 -04:00
import bundler from "./mod.ts";
2024-06-10 22:51:23 -04:00
import {Root} from "./introspect.ts"
2024-06-07 16:54:12 -04:00
const transpiled:Map<string, string> = new Map();
2024-06-10 22:51:23 -04:00
const ServeJS =(inText:string)=> new Response(inText, {headers:{"content-type":"application/javascript"}});
const htmlFile = Deno.readTextFileSync(Deno.cwd()+"/index.html");
2024-06-07 16:54:12 -04:00
Deno.serve(async(req)=>{
const url = new URL(req.url);
const index = url.pathname.lastIndexOf(".");
if(index > -1)
{
2024-06-10 22:51:23 -04:00
const ext = url.pathname.substring(index+1);
if(ext === "ts" || ext == "tsx" || ext == "js" || ext == "jsx")
2024-06-10 16:23:31 -04:00
{
2024-06-10 22:51:23 -04:00
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});
}
2024-06-10 16:23:31 -04:00
}
2024-06-07 16:54:12 -04:00
}
2024-06-10 22:51:23 -04:00
return new Response(htmlFile, {headers:{"content-type": "text/html"}});
2024-06-07 16:54:12 -04:00
});