动态导入的使用方法是什么?

What is the way to use dynamic imports?

我正在尝试使用动态导入 - import()

我读过这个dynamic-import documentations 看了这个 chrome devtools video,

仍然找不到正确的方法。

错误:

Uncaught (in promise) ReferenceError: module is not defined

样板文件:

我创建了一个新项目。

没有 webpack,没有任务运行器。

只是 运行 一个服务器 http-server 节点包和那些文件:

  1. index.html
  2. index.js
  3. a.js

index.html:

<button id="btn"> Lazy load a module</button>
<script src="index.js"></script>

index.js:

const btn = document.querySelector('#btn');

btn.addEventListener('click', event => {
  import('./a.js').then(module => { console.log(module) })
});

a.js

module.exports = { type: 'LazyModule'}

我在这里错过了什么?

动态导入函数来自 ECMAScript 标准,而 module.exports 是 commonjs 加载程序的一部分(如 browserify)

为了让它工作,你想在任何地方使用 ES 模块语法:

index.html: 添加type="module"到入口文件

<button id="btn"> Lazy load a module</button>
<script src="index.js" type="module"></script>

index.js:这个不错

a.js

export const type = 'LazyModule';

重要的是要注意浏览器中的模块解析方法与任何其他资产(指向 html 文件、图像等的链接)相同