试图按照官方手册实现一个模块,我得到这个错误信息。
未发现参考错误:exports未被定义
at app.js:2
但在我的代码中没有任何地方使用过exports
这个名字。
我怎样才能解决这个问题呢?
文件
let a = 2;
let b:number = 3;
import Person = require ('./mods/module-1');
export class Person {
constructor(){
console.log('Person Class');
}
}
export default Person;
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": false,
"sourceMap": true,
"outDir": "scripts/"
},
"exclude": [
"node_modules"
]
}
这个问题的几个其他解决方案
<script>var exports = {};</script>
如果你不再以`es5'为目标,这个答案可能不适用,我将尝试使答案更加完整。
如果CommonJS没有安装(它定义了exports
),你必须从你的tsconfig.json
中删除这一行。
"module": "commonjs",
根据评论,仅此一项可能无法适用于后来的`tsc'版本。如果是这样的话,你可以安装一个模块加载器,如CommonJS、SystemJS或RequireJS,然后指定它。
看一下tsc
生成的main.js
文件。你会发现这个文件在最上面。
Object.defineProperty(exports, "__esModule", { value: true });
这是错误信息的根源,删除"module": "commonjs",
后,它将消失。
我有同样的问题,并解决了它,在tsconfig.json中加入了"es5"库,像这样。
{
"compilerOptions": {
"target": "es5", //defines what sort of code ts generates, es5 because it's what most browsers currently UNDERSTANDS.
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true, //for angular to be able to use metadata we specify in our components.
"experimentalDecorators": true, //angular needs decorators like @Component, @Injectable, etc.
"removeComments": false,
"noImplicitAny": false,
"lib": [
"es2016",
"dom",
"es5"
]
}
}