以下是自定义针对 Vite + TypeScript 项目的完整路径别名配置流程:
以下是针对 Vite + TypeScript 项目的完整路径别名配置流程:
1. 安装必要依赖
bash
npm install -D @types/node
2. 配置 vite.config.ts
typescript
// vite.config.ts
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import path from 'path' // 需要 @types/node 支持
export default defineConfig({
plugins: [vue()],
resolve: {
alias: {
'@': path.resolve(__dirname, './src'),
// 可选:其他路径别名
'#': path.resolve(__dirname, './types')
}
}
})
3. 配置 tsconfig.json
json
{
"compilerOptions": {
"target": "ESNext",
"useDefineForClassFields": true,
"module": "ESNext",
"moduleResolution": "NodeNext",
"strict": true,
"jsx": "preserve",
"resolveJsonModule": true,
"isolatedModules": true,
"esModuleInterop": true,
"lib": ["ESNext", "DOM"],
"skipLibCheck": true,
"types": ["node"], // 添加 node 类型
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"],
"#/*": ["./types/*"]
}
},
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.vue"],
"references": [{ "path": "./tsconfig.node.json" }]
}
4. 配置 tsconfig.node.json
json
{
"compilerOptions": {
"composite": true,
"module": "ESNext",
"moduleResolution": "NodeNext",
"allowSyntheticDefaultImports": true,
"types": ["node"] // 确保包含 node 类型
},
"include": ["vite.config.ts"]
}
5. 配置项目结构验证
确保目录结构如下:
markdown
├─ src/
│ ├─ components/
│ │ └─ Layout1.vue
├─ types/
├─ vite.config.ts
├─ tsconfig.json
6. 重启开发服务器
bash
npm run dev
7. 验证配置是否生效
在代码中测试:
typescript
// src/main.ts
import { createApp } from 'vue'
import App from '@/App.vue' // 验证 @ 别名
createApp(App).mount('#app')
8. 常见问题解决方案
问题 1:TS2307 错误仍然存在
检查以下文件是否存在:
bash
ls src/components/Layout1.vue
问题 2:路径解析失败
在终端执行:
bash
npx vite inspect
查看输出的 resolve.alias 配置
问题 3:Node 类型报错
重新安装依赖:
bash
npm install -D @types/node
9. 完整类型声明文件配置
创建 src/vue.d.ts
:
typescript
// vue.d.ts
declare module '*.vue' {
import type { DefineComponent } from 'vue'
const component: DefineComponent<{}, {}, any>
export default component
}
// 路径别名类型声明
declare module '@/*' {
export * from '@/src/*'
}
10. 最终验证流程
- 确保所有配置文件保存
- 停止并重启开发服务器
- 检查控制台是否有编译错误
- 鼠标悬停导入路径查看是否解析正确
https://i.imgur.com/5tGm8C4.png
按照以上步骤完成后,@/components/Layout1.vue
的路径解析问题应该得到解决。如果仍然存在问题,可以检查:
- IDE 缓存:VS Code 执行
Ctrl+Shift+P
→Restart TS Server
- 文件命名:检查大小写是否一致 (Layout1.vue vs Layout1.Vue)
- 扩展名:是否在导入时遗漏了 .vue 扩展名
"module": "ESNext", 报错
改为
{
"compilerOptions": {
"composite": true,
"module": "NodeNext",
"moduleResolution": "NodeNext",
"allowSyntheticDefaultImports": true,
"types": ["node"] // 确保包含 node 类型
},
"include": ["vite.config.ts"]
}