打字稿参考错误:未定义导出 [英] Typescript ReferenceError: exports is not defined
问题描述
尝试按照 官方手册 实施模块,我收到此错误留言:
Trying to implement a module following the official handbook, I get this error message:
未捕获的引用错误:未定义导出
Uncaught ReferenceError: exports is not defined
在 app.js:2
但在我的代码中从来没有使用过名称exports
.
But nowhere in my code do I ever use the name exports
.
我该如何解决这个问题?
How can I fix this?
let a = 2;
let b:number = 3;
import Person = require ('./mods/module-1');
module-1.t
export class Person {
constructor(){
console.log('Person Class');
}
}
export default Person;
tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
"target": "es5",
"noImplicitAny": false,
"sourceMap": true,
"outDir": "scripts/"
},
"exclude": [
"node_modules"
]
}
推荐答案
如果您不再针对 es5
,此答案可能无效,我会尽量使答案更完整.
This answer might not work depending if you're not targeting es5
anymore, I'll try to make the answer more complete.
原答案
如果未安装 CommonJS(定义了exports
),你必须从你的 tsconfig.json
中删除这一行:
If CommonJS isn't installed (which defines exports
), you have to remove this line from your tsconfig.json
:
"module": "commonjs",
根据评论,仅此一项可能不适用于 tsc
的更高版本.如果是这种情况,您可以安装一个模块加载器,如 CommonJS、SystemJS 或 RequireJS,然后指定.
As per the comments, this alone may not work with later versions of tsc
. If that is the case, you can install a module loader like CommonJS, SystemJS or RequireJS and then specify that.
注意:
查看 tsc
生成的 main.js
文件.您会在最顶部找到它:
Look at your main.js
file that tsc
generated. You will find this at the very top:
Object.defineProperty(exports, "__esModule", { value: true });
它是错误信息的根源,去掉module":commonjs",
后,它就会消失.
It is the root of the error message, and after removing "module": "commonjs",
, it will vanish.
这篇关于打字稿参考错误:未定义导出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!