尝试按照官方手册实现一个模块,我得到这个错误消息:
Uncaught ReferenceError:未定义exports
在app.js: 2
但在我的代码中,我从未使用过名称exports。
我该如何解决这个问题?
文件
app.ts
let a = 2;
let b:number = 3;
import Person = require ('./mods/module-1');
模块- 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"
]
}
我在切换到“Node 16 + ESM + strict”tsconfig.json后不久就遇到了这个错误。
我认为ESM的改变是造成这种情况的原因。
我必须对文件进行等分,以找出根本原因:
exports.webhookTaskProcessor = functions.firestore
.document("items/{itemId}/tasks/{taskId}")
.onCreate((_change, context) => {
processItemTasks(context.params.itemId);
});
这就解决了问题:
export const webhookTaskProcessor = functions.firestore
.document("items/{itemId}/tasks/{taskId}")
.onCreate((_change, context) => {
processItemTasks(context.params.itemId);
});
如果错误信息更有用一点,那就太棒了。我希望这条面包屑对你有用。
我认为问题可能是配置不匹配。
下面的工作解决方案1为您提供了ES模块的正确配置。
下面的工作解决方案2为您提供了正确的CommonJS配置。
混合解决方案1+2给你一个错误。
为了清晰起见,我在这里只发布了部分内容。
Github项目https://github.com/jmmvkr/ts-express/
准备一套完整的文件来演示工作解决方案1和解决方案2。
工作方案1,ES模块
/* Configuration for ES Module */
// tsconfig.json
{
"compilerOptions": {
"module": "es6", // or "esnext"
}
}
// package.json
{
"type": "module", // type is module
}
工作解决方案2,CommonJS
/* Configuration for CommonJS */
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
}
}
// package.json
{
"type": "", // type is NOT module
}
混合,不工作
/* Mixed, got ReferenceError: exports is not defined in ES module scope */
// tsconfig.json
{
"compilerOptions": {
"module": "commonjs",
}
}
// package.json
{
"type": "module", // type is module
}
我有同样的问题,并解决了它添加“es5”库tsconfig。Json是这样的:
{
"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"
]
}
}