来源:vue3+vite+ts 识别不到路径映射配置问题 - 相遇就是有缘 - 博客园
用 Vue3 + Vite + TS 建的项目,通常有 tsconfig.json、tsconfig.app.json、tsconfig.node.json 三个配置文件。
tsconfig.json:
{
"files": [],
"references": [
{ "path": "./tsconfig.app.json" },
{ "path": "./tsconfig.node.json" }
]
}
tsconfig.app.json:
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
"target": "ES2020",
"useDefineForClassFields": true,
"module": "ESNext",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
"jsx": "preserve",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true
},
"include": ["src/**/*.ts", "src/**/*.tsx", "src/**/*.vue"]
}
tsconfig.node.json:
{
"compilerOptions": {
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
"target": "ES2022",
"lib": ["ES2023"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "Bundler",
"allowImportingTsExtensions": true,
"isolatedModules": true,
"moduleDetection": "force",
"noEmit": true,
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noUncheckedSideEffectImports": true,
},
"include": ["vite.config.ts"]
}
别名已经在 vite.config.ts 里配好:
resolve: {
alias: {
"@": path.resolve(__dirname, "src"),
},
}
按常规,接下来只要在 tsconfig.json 里加上映射关系就行:
{
"compilerOptions": {
"paths": {
"@/*":["src/*"]
},
"baseUrl": "."
}
}
但问题出现了:main.ts 识别的是 tsconfig.app.json 的映射,而不是 tsconfig.json 的;src/views/login/index.vue 这样的页面识别的却相反。只在 tsconfig.json 配,main.ts 报错;只在 tsconfig.app.json 配,Vue 页面报别名错:
找不到模块"@/components/xxx.vue"或其相应的类型声明。ts-plugin(2307)
目前想到的办法,是两个配置文件都配一份路径映射,这样就不报错了。
按理说只配一处就该生效,却没有效果,网上也没找到更好的说法。暂时记录在此,若有前端高手知道原因,欢迎留言。