如何使用 ts-jest 配置打字稿和使用 rootDir 的 ts-node
How to configure typescript with ts-jest and ts-node with rootDir
我有这个设置:
// tsconfig.json
{
"compilerOptions": {
"rootDir": "src",
...
}
...
//jest.config.ts
...
globals: {
'ts-jest': {
tsconfig: {
rootDir: '.'
}
}
}
但是当我 运行 开玩笑时,我收到一个错误提示,说打字稿文件需要在根目录下,似乎这个“rootDir”编译器选项被忽略了。
我不希望我的 /test 或我的配置位于 /src 下,我不希望它被编译到 /lib 或被发出。
我也不能使用 exclude
排除它,因为那样它也会排除我的 .ts 文件的类型,这些文件在项目之外,这使得使用 ts-node 非常困难。
您必须在 tsconfig.json 中指定 ts-node 配置。
// tconfig.json
{
"compilerOptions": {
"rootDir": "src",
...
"ts-node": {
"transpileOnly": true,
"files": true,
"compilerOptions": {
"rootDir": "."
}
}
}
...
// jest.config.ts
...
globals: {
'ts-jest': {
tsconfig: {
rootDir: '.'
}
}
}
您可以通过这种方式在 tsconfig.json 文件中为 ts-node 指定不同的 rootDir,这将使 ts-node 使用不同于通常 运行ning tsc.
当 运行ning ts-jest 实际上不是 ts-jest 时,您收到的发出错误是 ts-node 抱怨甚至在编译之前无法解析 jest 配置文件。当您 运行 jest
使用 jest.config.ts 文件时,它将使用 ts-node 编译该文件,然后将其传递给 ts-jest,后者将编译您的测试,然后它将通过那些 .js 测试开玩笑 运行 它。
这允许您为 ts-node 设置不同的 rootDir,这样您就可以 运行 .ts 文件而无需将它们编译到 /lib 中,也不必将它们存储在 /src 中。
我有这个设置:
// tsconfig.json
{
"compilerOptions": {
"rootDir": "src",
...
}
...
//jest.config.ts
...
globals: {
'ts-jest': {
tsconfig: {
rootDir: '.'
}
}
}
但是当我 运行 开玩笑时,我收到一个错误提示,说打字稿文件需要在根目录下,似乎这个“rootDir”编译器选项被忽略了。
我不希望我的 /test 或我的配置位于 /src 下,我不希望它被编译到 /lib 或被发出。
我也不能使用 exclude
排除它,因为那样它也会排除我的 .ts 文件的类型,这些文件在项目之外,这使得使用 ts-node 非常困难。
您必须在 tsconfig.json 中指定 ts-node 配置。
// tconfig.json
{
"compilerOptions": {
"rootDir": "src",
...
"ts-node": {
"transpileOnly": true,
"files": true,
"compilerOptions": {
"rootDir": "."
}
}
}
...
// jest.config.ts
...
globals: {
'ts-jest': {
tsconfig: {
rootDir: '.'
}
}
}
您可以通过这种方式在 tsconfig.json 文件中为 ts-node 指定不同的 rootDir,这将使 ts-node 使用不同于通常 运行ning tsc.
当 运行ning ts-jest 实际上不是 ts-jest 时,您收到的发出错误是 ts-node 抱怨甚至在编译之前无法解析 jest 配置文件。当您 运行 jest
使用 jest.config.ts 文件时,它将使用 ts-node 编译该文件,然后将其传递给 ts-jest,后者将编译您的测试,然后它将通过那些 .js 测试开玩笑 运行 它。
这允许您为 ts-node 设置不同的 rootDir,这样您就可以 运行 .ts 文件而无需将它们编译到 /lib 中,也不必将它们存储在 /src 中。