尝试按照官方手册实现一个模块,我得到这个错误消息:
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"
]
}
编辑:
这个答案可能不起作用,这取决于您是否不再针对es5,我将尝试使答案更完整。
原来的答案
如果CommonJS没有安装(它定义了exports),你必须从tsconfig.json中删除这一行:
"module": "commonjs",
根据注释,仅这一点可能不适用于tsc的后续版本。如果是这样的话,你可以安装一个模块加载器,比如CommonJS, SystemJS或RequireJS,然后指定它。
注意:
看看tsc生成的main.js文件。你会发现在最上面:
Object.defineProperty(exports, "__esModule", { value: true });
它是错误信息的根,删除"module": "commonjs",,它将消失。
我也犯了同样的错误。在我的例子中,这是因为我们在我们的TypeScript AngularJS项目中有一个老式的import语句,像这样:
import { IAttributes, IScope } from "angular";
它被编译成这样的JavaScript:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
这在以前是需要的,因为我们在代码中使用了IAttributes,否则TypeScript不知道该用它做什么。
但是在删除import语句并将IAttributes转换为ng之后。IAttributes这两行JavaScript代码消失了——错误消息也消失了。
我有类似的问题,原来的海报的问题:
我最好告诉你我犯了什么错误以及我是如何改正的,这可能会帮助到别人。
我有javascript nodejs项目,并将其转换为typescript。
之前的包装。我有“类型”:“模块”当我在JavaScript运行。
当我把它转换成TypeScript项目,并开始转换.ts文件中的文件,并使用以下命令开始运行:
npx tsc test.ts && node test.ts
我会得到上面的错误。
我通过简单地从package.json中删除“type”:“module”来摆脱这个错误
我的tsconfig。Json格式如下:
{
"compilerOptions": {
"target": "esnext",
"lib": ["es6", "es5", "es7", "dom"],
"allowJs": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"module": "es6",
"outDir": "./build",
"moduleResolution": "node",
"resolveJsonModule": true,
"skipLibCheck": true
},
"exclude": ["node_modules", "build"]
我使用节点14和TypeScript 4.2.4