Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to import es6 module that has been defined in <script type="module"> tag inside html?

I am able to define a module in my html file me.html:

<script type="module" id="DEFAULT_MODULE">   
           import Atom from './atom.js';       
           console.log("definition of getAtom")
           export default function getAtom(){
            return new Atom('atom');
           }
           console.log("exported getAtom")
</script>

Also see

  • https://blog.whatwg.org/js-modules
  • https://github.com/whatwg/html/pull/443#issuecomment-167639239

=> Is it possible to import that "anonymous" module to another module script in the same html file? Or to some "code behind"- JavaScript file that also has been loaded by the me.html file? The export seems to work; at least it does not throw any error.

For the import of the getAtom method I tried for example:

<script type="module">
    import getAtom from '.'; //this line does not work
    console.log("usage of getAtom")
    var atom = getAtom();             
</script>

I would expect some syntax like

 import getAtom;
 import getAtom from '.';
 import getAtom from window;
 import getAtom from './me.html';
 import getAtom from '.DEFAULT_MODULE';

However, none of these lines worked.

=>What is the correct syntax to reference the "anonymous" module if it is possible at all?

I use Chrome version 63.0.3239.108.

Related question:

How to dynamically execute/eval JavaScript code that contains an ES6 module / requires some dependencies?

like image 529
Stefan Avatar asked Dec 26 '17 18:12

Stefan


People also ask

How do I import a module in HTML?

In HTML, this is done by adding type="module" to the <script> tag. Modules are automatically interpreted in strict mode. There is also a function-like dynamic import() , which does not require scripts of type="module" .

Can you import modules in JavaScript?

You can import modules into a file in two ways, based on if they are named exports or default exports. Named exports are constructed using curly braces. Default exports are not.


1 Answers

As I understand, there is no way to import "anonymous" module, because "anonymous" module have no module specifier or individual url (its import.meta.url is just the html url as current spec). In theory it can be extended in the future, but I can not find the good use cases for such feature.

like image 61
hax Avatar answered Sep 28 '22 00:09

hax