Vue3+TS+Vite项目VS Code中@路径导入TS报错排查与解决
Vue3 + TypeScript + Vite项目@路径导入TS报错但运行正常的解决方法
问题场景
基于Vue3、TypeScript、Vite的项目,已安装Typescript Vue Plugin (Volar)、Vue 3 Snippets、Vue Language Features (Volar)插件。使用import InputText from '@/components/form/InputText.vue';导入组件时,VS Code提示Cannot find module '@/components/form/InputText.vue' or its corresponding type declarations.ts(2307),但项目实际运行正常;改用相对路径import InputText from '../form/InputText.vue'则无报错。
现有tsconfig配置
tsconfig.json
{ "references": [ { "path": "./tsconfig.node.json" }, { "path": "./tsconfig.app.json" } ] }
tsconfig.node.json
{ "extends": "@tsconfig/node18/tsconfig.json", "include": ["vite.config.*", "vitest.config.*", "cypress.config.*", "nightwatch.conf.*", "playwright.config.*"], "compilerOptions": { "composite": true, "noEmit": true, "module": "ESNext", "moduleResolution": "Bundler", "types": ["node"] } }
tsconfig.app.json
{ "extends": "@vue/tsconfig/tsconfig.dom.json", "include": ["env.d.ts", "src/**/*", "src/**/*.vue"], "exclude": ["src/**/__tests__/*"], "compilerOptions": { "composite": true, "noEmit": true, "baseUrl": ".", "paths": { "@/*": ["./src/*"] } } }
解决方案
在根目录的tsconfig.json中添加files: []配置即可解决该问题,修改后的配置如下:
{ "files": [], "references": [ { "path": "./tsconfig.node.json" }, { "path": "./tsconfig.app.json" } ] }
原因说明
当使用TypeScript的**项目引用(Project References)**时,若根tsconfig.json未指定files或include字段,TypeScript会默认尝试解析根目录下的所有文件,导致无法正确继承子配置tsconfig.app.json中的paths路径映射规则。添加files: []后,可明确告知TypeScript该配置仅用于管理项目引用,不会单独编译任何文件,从而让编辑器正确读取子配置中的路径映射,消除TS报错。
内容的提问来源于stack exchange,提问作者Mr.P
相关产品推荐
相关产品推荐

