Dynamic import on strings?
shawnmclean opened this issue · comments
Shawn Mclean commented
This is related to #76, if we are pulling this module via HTTP, this is essentially an HTTP request and evaluating the body as javascript.
What are the alternatives to dynamic import but allow us to evaluate a string as a module, let us handle the HTTP part ourselves?
Pauan commented
You can use Blob
to load any string or binary as a URL:
async function withBlob(blob, f) {
const url = URL.createObjectURL(blob);
try {
return await f(url);
} finally {
URL.revokeObjectURL(url);
}
}
function withJsString(string, f) {
return withBlob(new Blob([string], { type: "text/javascript" }), f);
}
You use it like this:
const exports = await withJsString("...", (url) => import(url));
Or if you already have a Blob
(from fetch
) then you can pass it directly:
const response = await fetch(...);
const blob = await response.blob();
const exports = await withBlob(blob, (url) => import(url));