我很难开玩笑地使用带有 import
语法的 ES 模块的打字稿项目。
我的项目最初是为 commonjs 编写的,jest 测试运行良好。但是后来我决定转用ES Modules(为了学习目的),jest不开心ヽ(`Д´)ノ
我使用的工具:typescript、jest、ts-jest
问题始于 import
语法。
以下是我尝试过的代码。
// projectRoot/src/app.ts
export default someFunction = (): void => {
// some code
}
如果
// projectRoot/__tests__/app.test.ts
import someFunction from '../src/app'; // without file extension
/* This execute perfectly fine */
但是
// projectRoot/__tests__/app.test.ts
import someFunction from '../src/app.ts' // with .ts
/*
● Test suite failed to run
__tests__/app.test.ts:1:25 - error TS2691: An import path cannot end with a '.ts' extension. Consider importing '../src/app' instead.
1 import information from '../src/app.ts';
*/
和
// projectRoot/__tests__/app.test.ts
import someFunction from '../src/app.js'; // with .js
/*
● Test suite failed to run
Cannot find module '../src/app.js' from '__tests__/app.test.ts'
*/
如上例,如果我导入带有扩展名的模块(这是 ES 模块必须的),jest(或者可能是 ts-jest?)会不高兴。 我在网上做了一些搜索,但似乎 jest doc 不太支持 ES 模块。这个 reading
同样适用于 ts-jest我的项目结构:
/projectRoot
├── /src/app.ts
├── /__tests__/app.test.ts
在 package.json 文件中有值 "type": "module"
tsconfig.json:
{
"compilerOptions": {
"target": "ES2015",
"module": "ESNEXT",
"outDir": "./build",
"strict": true,
"moduleResolution": "node",
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["./src"],
"exclude": ["node_modules", "**/*.test.ts"]
}
jest.config.js
export default {
"roots": [
//"<rootDir>/src"
"<rootDir>"
],
"testMatch": [
"**/__tests__/**/*.+(ts|tsx|js)",
"**/?(*.)+(spec|test).+(ts|tsx|js)"
],
"transform": {
"^.+\\.(ts|tsx)$": "ts-jest"
},
"preset": "ts-jest",
"testEnvironment": 'node'
}
请帮忙。谢谢。