Angular项目导入含构造函数的JS文件时Webpack报错排查
问题:Angular导入JS构造函数文件时Webpack抛出引用错误
问题详情
在Angular应用中导入一个包含构造函数的JS文件后,运行时Webpack抛出Uncaught ReferenceError错误。
相关代码
Assets目录下的test.js文件
TestServiceClient = function(arg1, arg2) { }; module.exports = TestServiceClient; module.exports.default = TestServiceClient;
Angular中的导入代码
var TestServiceClient = require('../assets/test'); @Injectable() export class ServiceTest { constructor() { const svc = new TestServiceClient('testarg1', 'testarg2'); } }
报错信息
Uncaught ReferenceError: TestServiceClient is not defined at 3472 (test.js:1:18) at __webpack_require__ (bootstrap:19:1)
问题原因
JS文件第一行的TestServiceClient = function(...)未使用var/let/const声明变量,而Angular与Webpack默认启用严格模式,严格模式禁止未声明的变量赋值,因此触发引用错误。
修复方案
- 修正JS文件的变量声明:给构造函数添加声明关键字,消除隐式全局变量问题,两种写法任选其一:
函数表达式写法:
函数声明写法:const TestServiceClient = function(arg1, arg2) { }; module.exports = TestServiceClient; module.exports.default = TestServiceClient;function TestServiceClient(arg1, arg2) { }; module.exports = TestServiceClient; module.exports.default = TestServiceClient; - 优化Angular导入语法(可选):改用TypeScript推荐的ES模块导入方式替代
require,更符合TS代码风格:import TestServiceClient from '../assets/test'; @Injectable() export class ServiceTest { constructor() { const svc = new TestServiceClient('testarg1', 'testarg2'); } }
内容的提问来源于stack exchange,提问作者Sachin Parashar
相关产品推荐
相关产品推荐

