简体   繁体   中英

Why can't modules be imported in standard JavaScript?

I need to use a Javascript library ( https://unpkg.com/troika-3d-text@0.19.0/dist/textmesh-standalone.esm.js?module ) which is only delivered as a module. When I try to import the class TextMesh in my non-module script build.js , the console gives me that error-message:

Cannot use import statement outside a module

So I needed to make build.js a module. But I have many non-module scripts, which are dependant from that build.js , which now also need to become modules. And I have many other non-module scripts, which are dependant from them, which then also need to become modules. And so on, ...

Where is my misunderstanding of the concept of JavaScript modules, because it can't be the intent of modules, that all scripts which are (in)directly dependant from that 'first' module, must become a module, too?!

You can use dynamic import() even in non-module scripts:

 (async()=>{ const { TextMesh } = await import("https://unpkg.com/troika-3d-text@0.19.0/dist/textmesh-standalone.esm.js?module"); console.log( TextMesh ); })();

Include the script attribute module :

<script type="module" src="jsFile.js"></script>

If you want to use the modules modules from a Node.js environment, name the files with the extension.mjs and use this command to run the file:

node --experimental-modules jsFile.mjs

You must tell the browser that the script is a module by using the type="module" attribute eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM