Import a module from string variable

There are limitations in the import syntax that make it difficult to do if not impossible without using external libraries.

The closest I could get is by using the Dynamic Import syntax. An example follows:

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<script>
    var moduleData = "export function hello() { alert('hello'); };";
    var b64moduleData = "data:text/javascript;base64," + btoa(moduleData);

</script>
<script type="module">

    async function doimport() {
      const module = await import(b64moduleData);
      module.hello();
    }

    doimport();

</script>

</body>
</html>

You will however notice that this has some limitations on the way the import code is constructed, which may not precisely match what you need. The simplest solution is probably to send the code of the module on the server for it to generate a temporary script to be then imported using a more conventional syntax.


let moduleData = await import("data:text/javascript,export function doSomething(str) { return str + '-done'; }");

and to test it

moduleData.doSomething('test');