动态加载不在脚本标签中的type ="module"? [英] Dynamically loading a module that is not in a script tag with type="module"?
问题描述
是否可以在没有用于该模块的脚本标签的情况下使用导入?
Is it possible to use import without a script tag already in place for said module?
我的问题是我想基于配置文件动态加载模块,例如:
My problem is that I want to load modules dynamically based on a config file, for example :
文件夹结构:
|-- main.js
|-- config.json.js
|-- modules
|-- module1.js
|-- module2.js
|-- module3.js
Index.html标题:
Index.html head :
<script src="/config.json.js" type="module"></script>
<script src="/main.js"></script>
config.json.js:
config.json.js :
export default {
modules : ['module1', 'module3']
}
main.js:
import config from '/config.json.js'
//Loading modules defined in config
config.modules.forEach(moduleName => {
import(`modules/${moduleName}`)
.then( module => {
console.log(`${module.name} loaded.`);
)}
})
由于未在script标签中定义模块,因此上述方法不起作用.
The above won't work as the modules haven't been defined in a script tag.
有什么方法可以使用香草JS并保持清洁吗?
Is there any way I can achieve this using vanilla JS and keeping it clean?
推荐答案
是的,只要您的加载程序脚本被标记为 module
Yes you can, as long as your loader script is marked as module
<script type="module">
const moduleSpecifier = './myModule.mjs';
import(moduleSpecifier)
.then((module) => {
// do something
});
</script>
不过,就您而言,简单的 forEach
可能还不够.如果要等待 all 模块从配置中加载,则可能需要 Promise.all
或类似的文件.
Although, in your case, a simple forEach
may not be enough. You may need Promise.all
or similar if you want to wait for all the modules to load from your config.
const modules = config.modules.map(moduleName => import(`modules/${moduleName}`))
Promise.all(modules)
.then(modules => {
// modules is an array of all your loaded modules
console.log('All modules loaded.');
)}
进一步阅读:
- https://jakearchibald.com/2017/es-modules-in-浏览器/
- https://developers.google.com/web/updates/2017/11/dynamic-import
这篇关于动态加载不在脚本标签中的type ="module"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!