这三个配置是 Vite 项目工程化中几乎必用的基础设施:路径别名让导入更加干净、可维护;环境变量区分不同部署环境;代理配置打通前后端联调的“最后一公里”。
路径别名(Path Alias)
默认的 ../../../ 相对导入在项目层级加深后极易混乱。路径别名能让你从任意文件使用固定前缀引入模块,提高可读性与重构效率。
配置方式:在 vite.config.ts 中设置 resolve.alias,同时同步 tsconfig.json 让 TypeScript 识别。
// vite.config.ts
import { defineConfig } from 'vite';
import path from 'path';
export default defineConfig({
resolve: {
alias: {
'@': path.resolve(__dirname, 'src'), // @ 指向 src 目录
'@components': path.resolve(__dirname, 'src/components'),
'@utils': path.resolve(__dirname, 'src/utils'),
},
},
});
// tsconfig.json(同步别名,确保编辑器智能提示)
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/*": ["src/*"],
"@components/*": ["src/components/*"],
"@utils/*": ["src/utils/*"]
}
}
}
使用效果:
// 原来:import Button from '../../../components/Button';
// 现在:
import Button from '@components/Button';
import { formatDate } from '@utils/date';
注意事项:
path是 Node 内置模块,需要安装@types/node以获得类型提示。- 路径别名在 Vite 的 CSS 预处理器(如 SCSS)中也需单独配置
css.preprocessorOptions,避免样式文件找不到变量。
环境变量(Environment Variables)
Vite 基于 .env 文件加载环境变量,并通过 import.meta.env 暴露给客户端。只有以 VITE_ 前缀的变量才会暴露,这是防止敏感信息泄露的安全机制。
文件命名规则(按优先级递增):
.env—— 所有环境共用.env.development—— 开发环境(vite命令).env.production—— 生产环境(vite build).env.local—— 本地私密配置(应加入.gitignore)
示例:
# .env.development
VITE_API_BASE_URL=http://localhost:3000/api
VITE_APP_TITLE=开发环境
// 在代码中使用
const baseURL = import.meta.env.VITE_API_BASE_URL;
console.log(import.meta.env.DEV); // 内置变量,判断是否开发模式
console.log(import.meta.env.PROD); // 是否生产模式
TypeScript 类型增强:新建 src/env.d.ts 或 vite-env.d.ts 声明自定义环境变量的类型。
/// <reference types="vite/client" />
interface ImportMetaEnv {
readonly VITE_API_BASE_URL: string;
readonly VITE_APP_TITLE: string;
}
interface ImportMeta {
readonly env: ImportMetaEnv;
}
代理配置(Proxy)
开发阶段前端端口(如 localhost:5173)与后端 API 端口(如 localhost:3000)不同,直接请求会遇到跨域问题。Vite 的 server.proxy 可以将指定路径的请求转发到目标服务器,绕过跨域限制。
// vite.config.ts
export default defineConfig({
server: {
port: 5173,
proxy: {
// 将所有 /api 开头的请求代理到后端服务
'/api': {
target: 'http://localhost:3000',
changeOrigin: true, // 修改请求头中的 Origin 为目标地址
rewrite: (path) => path.replace(/^\/api/, ''), // 可选:去掉 /api 前缀
},
// 代理 WebSocket(如热更新、实时通信)
'/socket.io': {
target: 'http://localhost:3000',
ws: true,
},
},
},
});
前端代码无需改动物理地址,只需像请求同源接口一样:
fetch('/api/users')
.then(res => res.json())
.then(data => console.log(data));
实际请求会被转发到 http://localhost:3000/users(如果使用了 rewrite)。
常见痛点解决:
- 代理不生效:检查请求路径是否匹配代理规则,确认
changeOrigin对某些后端校验 Origin 是必须的。 - 生产环境用不到代理:生产环境通常通过 Nginx 反向代理解决跨域,或后端配置 CORS。因此代理仅用于开发。
以上三项配置构成了 Vite 项目工程化的基础骨架,建议在新项目搭建时第一时间配置好,避免后续混乱。