开玩笑时打字稿路径无法解析?

时间:2018-10-17 17:52:02

标签: typescript jestjs tsconfig ts-jest

尝试使用convert this project开玩笑these instructions。除了使用paths配置的文件外,我一切正常:

"paths": {
      "@fs/*": ["./src/*"], 
      "@test/*": ["./test/*"]
    }

似乎在运行测试时,导入语句无法解析,并且已记录:

Cannot find module '@fs/container/validation/ValidationContext' from 'Core.spec.ts'

  1 | import { ValidationOptions } from "@fs/container/validation/ValidationOptions";
> 2 | import { ValidationContext } from "@fs/container/validation/ValidationContext";
    | ^
  3 | import { ValidationContainer } from "@fs/container/validation/ValidationContainer";
  4 | 
  5 | import { Core1 } from "@test/core/Core1";

  at Resolver.resolveModule (node_modules/jest-resolve/build/index.js:221:17)
  at Object.<anonymous> (test/core/Core.spec.ts:2:1)

在解决导入问题时,有没有办法使笑话/笑话包括@paths

3 个答案:

答案 0 :(得分:7)

我想将模块 paths~/ 开头解析为我的 <baseUrl>/<moduleName>

感谢 OJ Kwon 链接我解决了它(给他点)。

tsconfig.json

module-resolution path-mapping doc

{
  "compilerOptions": {
    "baseUrl": "src",
    "paths": {
      "~/*": ["*"]
    }
  },
}

玩笑配置

然后我们还需要告诉 jest 解析路径。它是通过以下配置完成的:

"moduleNameMapper": {
  "~/(.*)": "<rootDir>/src/$1"
},

答案 1 :(得分:1)

jest无法使用tsconfig的路径映射,因为它是ts编译器的时间,因此jest配置应具有相应的modulenamemapper(https://jestjs.io/docs/en/configuration.html#modulenamemapper-object-string-string)来解析别名路径。

答案 2 :(得分:1)

在根项目文件夹中添加 jest.config.js,内容如下。

const { pathsToModuleNameMapper } = require('ts-jest/utils')
const { compilerOptions } = require('./tsconfig')
module.exports = {
    preset: 'ts-jest',
    testEnvironment: 'node',
    moduleNameMapper: pathsToModuleNameMapper(compilerOptions.paths),
    modulePaths: [
        '<rootDir>'
    ],
}