This answer (/a/78617958/145072) shows that you can programmatically create modules at runtime by using new File
and URL.createObjectURL
.
Piggybacking off that question, is it possible to make these modules importable by one another, without a code transpilation step to rename imports?
For example, in this code example, is it possible to alter this code somehow so that it prints “in foo” and then “in bar”?
function createModule(filename: string, code: string) {
const file = new File([code], filename, { type: "text/javascript" });
const url = URL.createObjectURL(file)
return import(url)
}
const a = await createModule("foo.js", `
export function doFoo() {
console.log("in foo")
}
`);
const b = await createModule("bar.js", `
import foo from 'foo.js';
export function dobar() {
foo.doFoo();
console.log("in bar")
}
`);
console.log(b.dobar())
My thought process:
-
URL.createObjectURL
registers a URL with the window and creates a string that will load that URL — interesting that the string is not a data-url, it’s a UUID that maps to theFile
internally. That may be useful. -
The docs say it uses the same loading logic as
import
generally does. -
There seems to be no apparent mapping from the
filename
passed tonew File
and the URL created here. -
There might be a way that the window already internally aliases the two, or that we might be able to.
That’s all I’ve got.
2