0

Is it possible for browser javascript to create a new JS-file programmatically and then import it?

Here is some code that I tried out but didn't work:

const file = new File([`export function main() {console.log("AAA")}; main();`], "transpiled.js", {
    type: "text/javascript"
})
import("./transpiled.js") // this says: net::ERR_ABORTED 404 (Not Found)  
import("transpiled.js") // this says: Uncaught (in promise) TypeError: Failed to resolve module specifier 'transpiled.js'

The task is to get AAA as console output.

llesha
  • 423
  • 1
  • 15
  • 1
    Might be useful https://stackoverflow.com/questions/10343913/how-to-create-a-web-worker-from-a-string – Konrad Jun 16 '23 at 19:12
  • Why would you need to create a file? You can use `eval()` to execute JavaScript in a string. – Barmar Jun 16 '23 at 20:28

1 Answers1

0

For a static import you could check: Inlining ECMAScript Modules in HTML

A dynamic await import() is easy. You just prepare a global data:text/javascript string and import it.

What I like very much about this that this JS module code string is executed only once like a real JS module file.

For old browsers not supporting top-level module await you need to wrap your code in async IIFE.

<script>
  
  const src = `
    export function main(msg = 'AAA') {
      console.log(msg);
    } 
    
    main("I\'m executed on the module's import");
  `;
  window.TRANSPILED_JS = `data:text/javascript, ${src}`;
  
</script>
<script type="module">

  const {main} = await import(TRANSPILED_JS);
  main('I\'m a top level await');
  
</script>

<script type="module">

// for old browsers not supporting top-level await
(async () => {

  const {main} = await import(TRANSPILED_JS);
  main('I\'m an async IIFE');
  
})();
  
</script>
Alexander Nenashev
  • 8,775
  • 2
  • 6
  • 17