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

VS Code无法识别测试文件中TypeScript配置的paths别名怎么办?

问题根因

你当前配置的tsconfig.json中files字段仅声明了./src/index.ts一个入口文件,VSCode 搭载的 TypeScript 语言服务只会将纳入files/include范围的文件识别为项目成员,未被包含的测试文件(spec.ts)不会套用当前tsconfig的paths别名配置,因此抛出模块找不到错误。

修复步骤
  • 第一步:替换tsconfig.json中的files字段为include,覆盖所有需要识别别名的文件,示例配置如下:
{
  "compilerOptions": {
      "baseUrl": "src",
      "target": "es5",
      "module": "commonjs",
      "lib": [
          "es5",
          "es2015",
          "DOM"
      ],
      "moduleResolution": "Node",
      "outDir": "./dist/cjs",
      "declaration": true,
      "sourceMap": true,
      "esModuleInterop": true,
      "forceConsistentCasingInFileNames": true,
      "noImplicitAny": false,
      "removeComments": true,
      "strict": true,
      "paths": {
            "@common": ["common/index"],
            "@crashes": ["crashes/index"]
      }
  },
  "include": [
      "./src/**/*.ts", // 所有src下的ts源码
      "./**/*.spec.ts" // 所有后缀为.spec.ts的测试文件,可根据你的测试文件存放路径调整规则
  ]
}
  • 第二步:如果需要避免测试文件被打包到生产构建产物中,可以单独新增tsconfig.build.json用于生产编译,继承主配置后仅声明生产代码的包含规则即可:
{
  "extends": "./tsconfig.json",
  "include": ["./src/**/*.ts"],
  "exclude": ["./src/**/*.spec.ts"]
}

打包时执行tsc -p tsconfig.build.json即可。

  • 第三步:重启VSCode的TypeScript语言服务使配置生效,按下Ctrl+Shift+P(Mac系统为Cmd+Shift+P),输入并执行TypeScript: Restart TS Server即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 21:00:06