vite alias 配置 @
vite 项目 alias 如何配置,假如我还使用了 typescript
01 配置 Vite 的 Alias
在 vite.config.ts
中使用 resolve.alias
配置:
这里的配置可以更简单
'@': '/src'
import { defineConfig } from 'vite';
import path from 'path';
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, './src'), // 将 @ 映射到 src 目录
'~components': path.resolve(__dirname, './src/components') // 示例:映射到具体目录
}
}
});
02 配置 TypeScript 的 Path Alias
在 tsconfig.json
中同步配置 paths
{
"compilerOptions": {
"baseUrl": ".", // 设置基础路径
"paths": {
"@/*": ["src/*"], // 对应 Vite 的 @ 映射
"~components/*": ["src/components/*"] // 对应 Vite 的 ~components 映射
}
}
}
简单一点
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"]
}
}
}
03 注意事项
同步配置:Vite
和 TypeScript
的 alias
必须保持一致,避免开发和编译时的路径解析问题。
重启开发服务器:修改完成后需要重新启动 Vite 开发服务器确保生效。
import MyComponent from '@/components/MyComponent';