我试图解决这个问题已经走进了死胡同。我正在使用以下 TypeScript 配置:
{
"compilerOptions": {
"module": "es2022",
"moduleResolution": "nodenext",
"target": "es2017",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"noImplicitAny": true,
"outDir": "./dist",
"rootDir": "./src",
"typeRoots": [
"./src/types", "./node_modules/@types"],
"allowJs": true,
"strictFunctionTypes": true,
"noImplicitReturns": true
},
"include": ["./src/**/*"],
"exclude": ["node_modules"],
"ts-node": {
"esm": true,
"experimentalSpecifierResolution": true
}
}
Run Code Online (Sandbox Code Playgroud)
正如您所看到的, moduleResolution 设置为nodenext,因此我必须在导入时显式添加文件扩展名,如下所示: import ServerError from '../models/Errors/ServerError.js';。否则,我会收到一条错误消息,指出找不到该模块。
一切工作正常,但是当我启动测试时出现错误: Cannot find module '../models/Errors/ServerError.js' from '../src/services/usersService.ts'。所以基本上 jest 试图找到文件 ServerError.js,但它不存在,因为所有文件都有 .ts 扩展名,所以它应该是 ServerError.ts。如果我尝试将文件中的 .js 更改为 .ts,我也会收到错误。
由于这个问题,我无法完成我的任务,因此我将不胜感激。