有没有办法阻止 Intellisense 将所有 Mocha(或其他测试库)全局变量导入非测试文件?

Is there a way to stop Intellisense from importing all Mocha (or other test library) globals into non-test files?

我在同一目录中有这些文件。

package.json:

{
  "name": "example",
  "version": "1.0.0",
  "devDependencies": {
    "@types/mocha": "^7.0.1",
    "@types/node": "^13.7.1"
  }
}

tsconfig.json:

{}

index.ts:

export const test = () => 'test'

index.spec.ts:

import assert from 'assert'
import {test} from '.'

describe('test function', () => {
  it('should return test', () => assert.strictEqual(test(), 'test'))
})

即使不在 index.spec.ts 中使用 import 'mocha',Intellisense(在 VSCode 中)似乎也导入了 Mocha 全局变量,因此允许 describeitdescribeit 也可以在 index.ts 中使用。

有没有办法阻止它并允许我指定 Mocha 只应在 index.spec.ts 中导入?

我找到了一种方法,但不是很好:

tsconfig.json

{
  "include": ["**/*.ts"],
  "compilerOptions": {
    // put compiler options here
  }
}

tsconfig.src.json

{
  "extends": "./tsconfig.json",
  "include": ["**/*.ts"], // or wherever your source files are (e.g. src/**/*.ts)
  "exclude": ["**/*.spec.ts"],
  "compilerOptions": {
    // List all the types that the src folder needs
    // (should be everything except for mocha/jest/etc.)
    "types": ["node"]
  }
}

tsconfig.test.json

{
  "extends": "./tsconfig.json",
  "include": ["**/*.spec.ts"] // or wherever your tests are
  // Since asking this question I now put my tests in tests/**/*.ts
}

虽然 VSCode 将对所有文件使用 tsconfig.json,但如果您在源文件中使用了 describetest 等,您的构建脚本就可以使用:

package.json

{
  "name": "example",
  "version": "1.0.0",
  "scripts": {
    "build": "tsc -p tsconfig.src.json && tsc -p tsconfig.test.json"
  },
  "devDependencies": {
    "@types/mocha": "^7.0.1",
    "@types/node": "^13.7.1"
  }
}