如何在 Typescript 中排除编译文件但包含测试文件?

jon*_*nyc 7 typescript jestjs ts-jest

文件结构

函数/lib/src/...src .ts 文件
函数/lib/test/...测试文件
函数/tsconfig.json

当我在 tsconfig.json.include 中包含测试文件目录时,属性 linting 在我的测试文件中工作正常。但是,当我运行 tsc 时,测试文件被编译成 js。

当我从 tsconfig.json include 属性中删除测试目录时,我的所有 Jest 方法的测试文件中都会出现如下错误:

找不到名称“测试”。您需要为测试运行程序安装类型定义吗?尝试npm i @types/jestnpm i @types/mocha

tsconfig.json 如下所示

{
  "compilerOptions": {
    "module": "commonjs",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "outDir": "lib",
    "sourceMap": true,
    "strict": true,
    "target": "es2017"
  },
  "compileOnSave": true,
  "include": [
    "src",
  ],

}
Run Code Online (Sandbox Code Playgroud)

jest.config.js 如下所示

module.exports = {
  preset: 'ts-jest',
  testEnvironment: 'node',
};
Run Code Online (Sandbox Code Playgroud)

如何获得 Jest 方法识别并且不被编译测试文件所困扰?

Jos*_*ulf 1

这篇文章有一个对我有用的解决方案。

\n

您创建一个tsconfig.build.json扩展tsconfig.json文件的文件,其中包含以下内容:

\n
{\n  "extends": "./tsconfig.json",\n  // \xef\xb8\x8f this may vary depending on how you\n  // name your test files\n  "exclude": [\n    "lib/test/*",\n  ]\n}\n
Run Code Online (Sandbox Code Playgroud)\n

然后,您的法线tsconfig.json用于测试运行程序,并使用以下命令转换您的文件:

\n
tsc --project tsconfig.build.json\n
Run Code Online (Sandbox Code Playgroud)\n

您可以将该命令作为脚本添加到package.json构建命令中。

\n