【发布时间】:2021-05-15 04:17:26
【问题描述】:
我很难开玩笑地使用带有import 语法的 ES 模块的 typescript 项目。
我的项目最初是为 commonjs 编写的,开玩笑的测试运行良好。但是后来我决定改用ES Modules(学习目的),开玩笑不开心ヽ(`Д´)ノ
我正在使用的工具: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?)会不高兴。 我在网上做了一些搜索,但似乎开玩笑 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'
}
请帮忙。谢谢。
【问题讨论】:
-
你有 github repo 的链接吗?
-
嗨@geodoo,这是我的回购https://github.com/koonfoon/ts-jest-code-test
-
有人解决了这个问题吗?
-
@Rafael 请在下面查看我的回答。希望对您有所帮助。
标签: typescript jestjs ts-jest