You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

TypeScript项目同目录源码与测试文件分tsconfig及VS Code兼容方案

解决方案:拆分TS配置并同步工具链

1. 拆分TS配置文件

通过继承式配置避免重复代码,同时明确区分生产/测试规则:

  • 根目录创建tsconfig.base.json(公共基础配置):
{
  "compilerOptions": {
    "target": "ESNext",
    "module": "CommonJS",
    "outDir": "./dist",
    "strict": true,
    "moduleResolution": "node",
    "esModuleInterop": true,
    "skipLibCheck": true
  }
}
  • 根目录tsconfig.json(生产环境配置,继承基础):
{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "noImplicitAny": true
  },
  "include": ["./ts/**/*.ts"],
  "exclude": ["./ts/**/*.spec.ts"]
}
  • 根目录创建tsconfig.test.json(测试环境配置,继承基础):
{
  "extends": "./tsconfig.base.json",
  "compilerOptions": {
    "noImplicitAny": false,
    "sourceMap": true
  },
  "include": ["./ts/**/*.ts"]
}

2. 配置VS Code同步规则

VS Code会自动根据文件所属的include范围匹配对应TS配置,需确保以下几点:

  • 安装项目本地TypeScript依赖:npm install typescript --save-dev,避免全局版本不一致
  • 在.vscode/settings.json中指定使用项目本地TS:
{
  "typescript.tsdk": "./node_modules/typescript/lib"
}
  • 若出现缓存错误,按Ctrl+Shift+P执行TypeScript: Restart TS Server强制刷新

3. 同步ESLint配置

让ESLint针对生产/测试文件分别加载对应TS配置,在.eslintrc.js中用overrides区分规则:

module.exports = {
  root: true,
  parser: "@typescript-eslint/parser",
  plugins: ["@typescript-eslint"],
  rules: {
    // 基础通用规则
  },
  overrides: [
    // 生产代码规则
    {
      files: ["ts/**/*.ts"],
      excludedFiles: ["**/*.spec.ts"],
      parserOptions: {
        project: "./tsconfig.json"
      },
      rules: {
        "@typescript-eslint/no-explicit-any": "error"
      }
    },
    // 测试代码规则
    {
      files: ["ts/**/*.spec.ts"],
      parserOptions: {
        project: "./tsconfig.test.json"
      },
      rules: {
        "@typescript-eslint/no-explicit-any": "off"
      }
    }
  ]
};

4. 构建/测试命令对齐配置

在package.json中添加明确命令,确保工具链使用正确的TS配置:

{
  "scripts": {
    "build": "tsc -p tsconfig.json",
    "test:type-check": "tsc -p tsconfig.test.json --noEmit",
    "test": "npm run test:type-check && jest"
  }
}

常见问题排查

  • VS Code报不存在的错误:优先重启TS服务,大概率是缓存导致
  • ESLint与TS规则不一致:检查parserOptions.project是否指向对应TS配置文件
  • 测试文件无法引用生产代码:确认tsconfig.test.json的include包含生产代码目录

内容的提问来源于stack exchange,提问作者Daniel Kaplan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 16:42:32