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

如何在HTML的JS脚本中导入自制JavaScript模块?

自定义模块导入问题排查与解决

我尝试导入自己编写的测试模块,但运行时出现了多个错误,具体情况如下:

模块代码(testmodule.js)

export class Test {
    static printTest() {
        console.log("it works");
    }
}

初始HTML配置

<!doctype html>
<html>
    <head>
    </head>
    <body>
        <script type="module" src="testmodule.js"></script>
        <script src="script.js"></script>
    </body>
</html>

第一次尝试:直接调用模块方法(script.js)

Test.printTest();

错误信息:Uncaught ReferenceError: Test is not defined

第二次尝试:在脚本中导入模块(更新后的script.js)

import Test from "moduletest";
Test.printTest();

错误信息:Uncaught SyntaxError: import declarations may only appear at top level of a module


问题原因与解决方法

1. 模块作用域隔离

ES模块默认采用隔离作用域,模块内的变量、类不会自动暴露到全局。直接在HTML中引入testmodule.js,普通脚本(未声明type="module"的script.js)无法访问模块内的Test类。

2. 普通脚本不支持import语法

只有声明了type="module"的脚本才能使用import/export语法,否则会抛出语法错误。

3. 导入语法错误

你的模块使用的是命名导出(export class Test),对应的导入应该使用命名导入,而非默认导入。


正确实现方式

方式一:将script.js改为模块脚本

  1. 修改script.js的导入语法:
// 注意文件路径要正确,这里假设testmodule.js和script.js在同一目录
import { Test } from './testmodule.js';
Test.printTest();
  1. 更新HTML,给script.js添加type="module":
<!doctype html>
<html>
    <head>
    </head>
    <body>
        <script type="module" src="script.js"></script>
    </body>
</html>

方式二:将模块类暴露到全局(不推荐)

如果非要在普通脚本中访问模块内容,可以手动将Test挂载到window对象,但这种做法会破坏模块的隔离性,不建议在生产环境使用:
修改testmodule.js:

export class Test {
    static printTest() {
        console.log("it works");
    }
}

// 将Test暴露到全局
window.Test = Test;

此时HTML可以保持初始写法,script.js就能正常调用Test.printTest()。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 14:01:05