vscode 智能感知导入在 jest ts 测试中不起作用

uTI*_*Ity 6 import javascript-intellisense jestjs visual-studio-code

在我的整个项目中,VSCode 会自动提示导入类型(出现黄色灯泡)。除了在 JEST 测试文件中(在我的测试目录中),我没有灯泡。我可以手动编写导入,此时会检测到同一文件中的任何进一步导入。

有谁知道如何解决这一问题?

问候, 蒂莉

小智 6

I was experiencing the same issue, Matt Bierner's response got me to the correct solution.

The Problem

I had this project layout:

./lib/
./src/
./tests/
./tsconfig.json
Run Code Online (Sandbox Code Playgroud)

In my tsconfig I had:

{
  "compilerOptions": {
    ...
    "outDir": "./lib",
    "typeRoots": ["./node_modules/@types"]
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}
Run Code Online (Sandbox Code Playgroud)

It was the tests being excluded, i.e. "**/*.spec.ts", which was preventing vscode from suggesting imports inside the tests.

Obviously, when this was removed, when build ran, the tests would end up in my ./lib output dir.

I discovered a better solution to remedy both problems.

The Solution

I split the tsconfig.json as follows:

./lib/
./src/
./src/tsconfig.json
./tests/
./tsconfig.base.json
./tsconfig.json
./package.json
Run Code Online (Sandbox Code Playgroud)

The ./tsconfig.base.json file:

{
  "compilerOptions": {
    ...
    "outDir": "./lib",
    "typeRoots": ["./node_modules/@types"]
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "**/*.spec.ts"]
}
Run Code Online (Sandbox Code Playgroud)

The ./tsconfig.json file:

{
  "extends": "./tsconfig.base.json"
}
Run Code Online (Sandbox Code Playgroud)

The ./src/tsconfig.json file:

{
  "extends": "../tsconfig.base.json",
  "compilerOptions": {
    "outDir": "../lib"
  },
  "exclude": ["node_modules", "lib", "**/*.spec.ts"]
}
Run Code Online (Sandbox Code Playgroud)

The build script was modified so that it would use the ./src/tsconfig.json file, which required the -p ./src/ part to be added, as per the example below.

The ./package.json file:

{
  ...
  "scripts": {
      ...
      "build": "tsc -p ./src/"
      ...
    }
  ...
}
Run Code Online (Sandbox Code Playgroud)

I hope this helps anyone that has the same issue.

  • 这对我有帮助,但必须有更好的方法,我经常遇到这个问题,但似乎找不到任何真正的提及。人们如何处理它超出我的范围 (6认同)