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

如何配置Neovim + LSP以读取多个tsconfig文件的类型信息?

解决Neovim LSP无法识别多TSConfig文件的问题

方法一:配置TSServer自动匹配对应TSConfig(推荐)

Neovim的tsserver默认只会加载根目录的tsconfig.json,需要让它根据当前打开的文件类型自动切换配置。修改你的tsserver LSP配置,添加逻辑判断:

require('lspconfig').tsserver.setup({
  settings = {
    typescript = {
      tsconfigPath = function(root_dir)
        local buf_name = vim.api.nvim_buf_get_name(0)
        -- 判断当前文件是否为测试文件(路径包含__tests__或后缀为.test.ts/.test.tsx)
        local is_test_file = string.find(buf_name, '__tests__') ~= nil or string.match(buf_name, '%.test%.tsx?$') ~= nil
        return is_test_file and (root_dir .. '/tsconfig.test.json') or (root_dir .. '/tsconfig.json')
      end
    }
  }
})

这段代码会自动检测当前打开的文件是否是测试文件,是的话加载tsconfig.test.json,否则用主配置。

方法二:通过TS复合项目关联配置

利用TypeScript的项目引用功能,让主配置关联测试配置,这样tsserver会自动识别到测试相关的类型定义:

  1. 修改tsconfig.test.json,添加composite: true(项目引用要求被引用的配置开启复合模式):
{
  "extends": "./tsconfig.json",
  "compilerOptions": {
    "types": ["vitest/globals", "@testing-library/jest-dom"],
    "composite": true
  },
  "include": [
    "src/**/__tests__/**/*.test.ts",
    "src/**/__tests__/**/*.test.tsx",
    "setupTests.ts"
  ],
  "exclude": ["node_modules"]
}
  1. 在主tsconfig.json中添加references字段:
{
  // 原有配置...
  "references": [{"path": "./tsconfig.test.json"}]
}

方法三:手动切换TSConfig(临时方案)

打开测试文件后,执行tsserver提供的命令手动指定配置文件:

:TSSetTsConfig ./tsconfig.test.json

这个方法每次打开测试文件都需要手动操作,适合临时调试场景。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.02 16:12:31