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

ExpressJS+TypeScript+Vitest测试时VS Code中tsconfig配置不生效问题

问题原因

两个问题的核心都是tsconfig路径配置错误+Vitest默认转译规则不兼容TypeORM装饰器,不存在VS Code本身的Bug,也不需要提前构建产物再跑测试。

  • 第一个IDE报错问题:test/tsconfig.json 内的相对路径是相对于配置文件自身所在目录解析的,原配置里写的 ./src/**/*.ts 实际指向不存在的 test/src/ 目录,导致该配置没有匹配到任何有效文件,VS Code的TypeScript服务会自动回退使用根目录的tsconfig,而根目录配置仅包含src目录、未引入Vitest全局类型,自然报类型错误。
  • 第二个TypeORM导入报错问题:一是继承根目录tsconfig后rootDir仍指向./src(相对test目录的错误路径),模块解析逻辑异常;二是Vitest默认使用esbuild转译TS,不支持TypeORM依赖的装饰器元数据输出,转译产物不兼容导致报错。
修复步骤

1. 调整tsconfig配置

优先把测试专用tsconfig移到项目根目录,命名为tsconfig.test.json,避免嵌套路径解析问题,调整后项目结构:

src/
    app.ts
test/
    integration/
        example.spec.ts
vitest.config.ts
tsconfig.json
tsconfig.test.json

根目录生产用tsconfig.json配置:

{
  "extends":"@tsconfig/node16/tsconfig.json",
  "compilerOptions": {
    "rootDir": "./src",
    "outDir": "./build",
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "resolveJsonModule": true,
    "noEmitOnError": true
  },
  "include": ["./src/**/*.ts"],
  "references": [{ "path": "./tsconfig.test.json" }]
}

根目录测试用tsconfig.test.json配置:

{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "rootDir": "./",
    "noEmit": true,
    "types": ["vitest/globals", "node"]
  },
  "include": [
    "./src/**/*.ts",
    "./test/**/*.ts",
    "./vitest.config.ts"
  ]
}

如果要保留test目录下的tsconfig,只需要把include里的路径改成../src/**/*.ts,同时覆盖compilerOptions里的rootDir为..即可。

2. 配置VS Code使用项目本地TS版本

在根目录新建.vscode/settings.json,强制IDE使用项目依赖里的TS版本,避免内置版本和项目版本差异导致配置解析失败:

{
  "typescript.tsdk": "node_modules/typescript/lib",
  "typescript.enablePromptUseWorkspaceTsdk": true
}

配置完成后重启VS Code的TS服务(按Ctrl+Shift+P调出命令面板,执行TypeScript: Restart TS Server)即可消除IDE类型错误。

3. 修复Vitest转译兼容TypeORM的问题

安装SWC转译依赖替换默认的esbuild,支持装饰器元数据输出:

pnpm add -D @swc/core unplugin-swc

修改根目录vitest.config.ts配置:

import swc from 'unplugin-swc'
import { defineConfig } from 'vitest/config'

export default defineConfig({
  plugins: [
    swc.vite({
      jsc: {
        parser: {
          syntax: 'typescript',
          decorators: true
        },
        transform: {
          legacyDecorator: true,
          decoratorMetadata: true
        }
      }
    })
  ],
  test: {
    globals: true,
    include: ['test/**/*.spec.ts']
  }
})

4. 调整执行脚本

把package.json里的测试脚本改成直接在根目录执行,不需要cd到test目录:

{
  "scripts": {
    "test": "vitest run",
    "test:watch": "vitest"
  }
}

直接执行pnpm test即可跑通测试,不需要提前执行构建命令。

注意事项
  • 所有tsconfig里的相对路径永远以当前配置文件所在目录为起点,不要以执行命令时的终端目录为起点写路径。
  • 测试场景直接跑TS源码即可,不需要依赖build目录的构建产物,搭配Vitest的转译插件可以直接处理装饰器、路径别名等TS特性。
  • 若配置路径别名,需要同时在tsconfig的compilerOptions.paths和vitest.config的resolve.alias里同步配置,保证IDE和运行时解析逻辑一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 23:09:24