Lau*_*kik 9 typescript jestjs ts-jest
这是下面的演示代码,用于演示我在当前项目中遇到的失败。
它编译并运行,只是无法使用笑话进行编译,并出现以下错误
错误:错误 TS1343:仅当“--module”选项为“es2020”、“es2022”、“esnext”、“system”、“node16”或“nodenext”时,才允许使用“import.meta”元属性。
文件:src/calc.ts
import { fileURLToPath } from 'url';
import path from 'path';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
export function add(x: number, y: number): number {
return x + y;
}
export function mul(x: number, y: number): number {
return x * y;
}
Run Code Online (Sandbox Code Playgroud)
jest.config.cjs:
module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
};
Run Code Online (Sandbox Code Playgroud)
tsconfig.json:
{
"include": [
"./src/**/*"
],
"exclude": [
"node_modules"
],
"compilerOptions": {
"target": "ES2022",
"module": "NodeNext",
"outDir": "./out",
"rootDir": "./src",
"strict": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
}
}
Run Code Online (Sandbox Code Playgroud)
包.json
"devDependencies": {
"@types/jest": "^26.0.24",
"jest": "^26.6.3",
"ts-jest": "^26.5.6",
"typescript": "^4.7.4"
}
Run Code Online (Sandbox Code Playgroud)
不确定我在这里是否做错了什么
小智 3
假设我们正在讨论使用 test 来运行测试,我找到了错误的原因,但我不知道如何解决它。
您的"module": "NodeNext"选项将被忽略,因为jest注册ts-node了"module": "CommonJS"
/// packages/jest-config/src/readConfigFileAndSetRootDir.ts
// Register TypeScript compiler instance
const tsNode = await import('ts-node');
return tsNode.register({
compilerOptions: {
module: 'CommonJS',
},
moduleTypes: {
'**': 'cjs',
},
});
Run Code Online (Sandbox Code Playgroud)
查看jest 源代码
这就是为什么错误提到这nodenext是一个有效的选择,即使您实际上在tsconfig.json.