TypeScript转译后运行报jQuery未加载的RequireJS错误如何解决
报错根本原因
你遇到的报错是因为TypeScript默认编译输出了CommonJS格式的代码,其使用的require()语法是Node.js专属的模块引入方式,浏览器本身不支持,同时你搭配使用的RequireJS是AMD规范的模块加载器,无法解析CommonJS格式的引入逻辑,因此触发了模块未加载的错误。
解决方案1:直接使用全局jQuery(最简便,适合小型项目)
你已经通过CDN引入了jQuery,全局window上已经挂载了$对象,完全不需要再用模块导入的方式引入,按如下步骤修改即可:
- 在你的TS文件头部添加全局类型声明,替换原来的
import * as $ from "jquery"代码:
declare var $: JQueryStatic; export class Loading { // 保留原来的类逻辑不变 public showLoadingModal(msg?: string) { if (msg === undefined) { msg = "Loading ..."; } $("#dialog1 label").html(msg); } // 其余方法保持不变 }
- 不需要再配置RequireJS,直接保留原来的script标签引入jQuery和编译后的JS文件即可,编译后的代码不会再出现
require("jquery")的逻辑,报错会直接消失。
解决方案2:适配AMD规范配合RequireJS使用
如果你需要保留模块导入的写法,按如下步骤调整:
- 修改你的
tsconfig.json配置,将module字段设置为AMD,让TS编译输出符合RequireJS规范的代码:
{ "compilerOptions": { "target": "ES5", "module": "AMD", "esModuleInterop": true, "skipLibCheck": true, "forceConsistentCasingInFileNames": true } }
- 修改HTML中的引入逻辑,不要直接用script标签引入编译后的
helloworld.js,改为通过RequireJS加载:
<script src="https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.6/require.min.js"></script> <script> requirejs.config({ paths: { jquery: "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min" } }); // 加载你的模块 requirejs(["helloworld"], function(helloworld) { // 这里可以正常使用导出的Loading类 const loading = new helloworld.Loading(); loading.showLoadingModal(); }); </script>
- 移除原来手动声明的
var exports = {}代码,AMD格式的编译代码会自动处理导出逻辑。
解决方案3:使用ES模块规范(适合现代浏览器)
如果不需要兼容老版本浏览器,可以直接用浏览器原生支持的ES模块规范:
- 修改
tsconfig.json的module字段为ESNext,moduleResolution为Node - 引入script标签时添加
type="module"属性,同时配置importmap映射jQuery的CDN地址:
<script type="importmap"> { "imports": { "jquery": "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" } } </script> <script type="module" src="helloworld.js"></script>
内容的提问来源于stack exchange,提问作者Yashpal S
相关产品推荐
相关产品推荐

