You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确使用Dynamic Imports?遇module未定义报错求助

解决动态import()报错:Uncaught (in promise) ReferenceError: module is not defined

这个报错我之前也碰到过!问题核心在于:浏览器原生的动态import()只能加载ES模块(用export语法导出的模块),如果你的a.js用了Node.js的CommonJS语法(比如module.exports),浏览器根本不认识module这个全局变量,自然就报错了。结合你的纯前端无打包工具的场景,给你一步步的解决方案:

1. 给主脚本声明ES模块类型

首先在index.html里,引入index.js的时候必须加上type="module"属性,告诉浏览器这是一个ES模块文件:

<!DOCTYPE html>
<html>
<head>
    <title>Lazy Load Demo</title>
</head>
<body>
    <button id="btn">Lazy load a module</button>
    <!-- 关键:添加type="module" -->
    <script type="module" src="index.js"></script>
</body>
</html>

2. 把a.js改成ES模块格式

把a.js里的module.exports替换成ES模块的export语法,比如:

// a.js - 用ES模块导出内容
export const greet = "Hello from lazy loaded module!";

// 如果是导出函数
export function showGreet() {
    alert(greet);
}

3. 正确使用动态import()

在index.js里用异步方式处理动态加载(因为import()返回的是Promise),可以用async/await或者.then()语法:

// index.js
const btn = document.getElementById('btn');

btn.addEventListener('click', async () => {
    try {
        // 动态加载a.js,路径是相对当前脚本的位置
        const lazyModule = await import('./a.js');
        console.log(lazyModule.greet);
        lazyModule.showGreet();
    } catch (error) {
        console.error('模块加载失败:', error);
    }
});

几个要注意的细节

  • 绝对不能用file://协议直接打开index.html,必须用http-server启动服务,ES模块要求在HTTP/HTTPS环境下运行。
  • 动态import的路径要写对,是相对于当前执行脚本(index.js)的相对路径,别写错了。
  • 如果你之前习惯了CommonJS的写法,现在必须切换到ES模块的export/import语法,因为浏览器原生不支持CommonJS,除非你用打包工具转译,但你这里没有webpack之类的工具,所以只能用ES模块。

内容的提问来源于stack exchange,提问作者ueeieiie

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:36:37