Appearance
Vue3 + TypeScript 项目中配置路径别名
问题背景
在 Vue + TypeScript + Vite 项目中,随着目录层级加深,导入路径会变得很长:
ts
import MyComponent from '../../../components/MyComponent.vue'
import '../../../styles/layout.scss'../../../ 这种相对路径难以阅读和维护。我们更希望用 @ 开头的别名来简化:
ts
import MyComponent from '@/components/MyComponent.vue'
import '@/styles/layout.scss'但直接这样写会报错:
Cannot find module '@/components/MyComponent.vue' or its corresponding type declarations.需要同时在 Vite 和 TypeScript 两处配置。
Vite 侧配置
Vite 负责实际的模块解析,需要在 vite.config.ts 中通过 resolve.alias 配置路径映射:
ts
import { fileURLToPath } from 'node:url'
import { defineConfig } from 'vite'
export default defineConfig({
resolve: {
alias: {
'@': fileURLToPath(new URL('./src', import.meta.url)),
},
},
})fileURLToPath(new URL('./src', import.meta.url)) 等价于 path.resolve(__dirname, 'src'),但 ESM 项目中没有 __dirname,这种方式是 Vite 官方推荐的写法。
配置后,Vite 在打包时会将 @/xxx 解析为 src/xxx,import 就能正常工作了。
TypeScript 侧配置
Vite 配置只解决了运行时的模块解析,但 TypeScript 编译器并不认识 @,仍然会报类型错误。需要在 tsconfig.json 中添加 paths 映射:
json
{
"compilerOptions": {
"paths": {
"@/*": ["./src/*"]
}
}
}@/* 匹配所有 @/ 开头的导入,映射到 ./src/*。
TypeScript 编译器在检查 import '@/components/MyComponent.vue' 时,会根据 paths 规则将其解析为 src/components/MyComponent.vue,从而消除类型错误。
生效原理
整个路径别名的生效涉及两层:
- Vite 层(运行时):
vite.config.ts的resolve.alias让 Vite 在打包时能正确解析@路径 - TypeScript 层(编译检查):
tsconfig.json的paths让 TypeScript 在类型检查时能正确识别@路径
两者缺一不可。只配 Vite 不配 TypeScript,IDE 会报红线;只配 TypeScript 不配 Vite,打包时会找不到模块。
可以把它理解为:Vite 负责 “真正找到文件”,TypeScript 负责 “不报错”。两者各司其职,共同让路径别名正常工作。