Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
414 views
in Technique[技术] by (71.8m points)

javascript - 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

=> 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...