【问题标题】:What is the way to use dynamic imports?使用动态导入的方法是什么?
【发布时间】:2018-04-11 07:55:15
【问题描述】:

我正在尝试使用动态导入 - 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'}

我在这里错过了什么?

【问题讨论】:

    标签: javascript html dynamic-import


    【解决方案1】:

    动态导入功能来自 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 文件、图像等的链接)的方法相同

    【讨论】:

    • 谢谢,它成功了 :) 我的惰性模块是 a.js,那么为什么我需要将 type=module 添加到 index.js?
    • 浏览器需要知道将第一个文件视为一个ES Module,然后才能从其他ES Modules导入符号
    猜你喜欢
    • 2010-09-30
    • 2012-10-12
    • 2023-01-19
    • 2015-02-16
    • 2022-10-20
    • 2012-07-23
    • 2020-03-12
    • 2017-04-03
    • 2016-10-27
    相关资源
    最近更新 更多