《Vue3 从入门到大神20篇》环境变量与跨域处理 —— Vite 的配置秘籍

发布时间:2026/7/3 16:59:02
《Vue3 从入门到大神20篇》环境变量与跨域处理 —— Vite 的配置秘籍 前言在本地开发时你的接口请求可能是这样的axios.get(http://192.168.1.100:8080/api/users)但部署到生产环境后后端地址变成了https://api.example.com/api/users如果你把 IP 和端口硬编码在代码里那每次部署都要改代码——这显然是不可接受的。同时本地开发还会遇到另一个经典问题浏览器报跨域错误CORS这两个问题本质上都属于环境配置与构建工具的能力范畴。在 Vue3 Vite 体系中它们有非常优雅的解决方案。这一篇我们把.env环境变量、Vite Proxy 代理、多环境管理、部署注意事项​ 一次性讲透。一、环境变量让代码适应不同环境1️⃣ Vite 的环境变量机制Vite 使用import.meta.env​ 来暴露环境变量console.log(import.meta.env.VITE_API_BASE_URL)核心规则只有VITE_开头的变量才会暴露到客户端代码中。2️⃣ 创建环境文件在项目根目录下创建.env # 所有环境共用 .env.development # 开发环境 .env.production # 生产环境 .env.staging # 预发布环境可选3️⃣ 文件内容示例# .env.development VITE_API_BASE_URL/api VITE_APP_TITLEVue3 Demo (Dev) VITE_UPLOAD_LIMIT10# .env.production VITE_API_BASE_URLhttps://api.example.com VITE_APP_TITLEVue3 Demo VITE_UPLOAD_LIMIT504️⃣ 在代码中使用// utils/request.ts const request axios.create({ baseURL: import.meta.env.VITE_API_BASE_URL, timeout: 10000 })script setup console.log(import.meta.env.VITE_APP_TITLE) /script5️⃣ TypeScript 类型提示进阶// env.d.ts interface ImportMetaEnv { readonly VITE_API_BASE_URL: string readonly VITE_APP_TITLE: string readonly VITE_UPLOAD_LIMIT: string } interface ImportMeta { readonly env: ImportMetaEnv }✅IDE 自动补全 类型校验二、模式Mode与环境切换1️⃣ Vite 的默认模式命令默认模式加载文件vite devdevelopment.env.developmentvite buildproduction.env.production2️⃣ 自定义模式// package.json { scripts: { dev: vite --mode development, build:staging: vite build --mode staging, build: vite build --mode production } }--mode决定加载哪个.env文件三、跨域问题为什么本地开发会跨域1️⃣ 跨域的本质浏览器出于安全考虑阻止了前端http://localhost:5173 后端http://192.168.1.100:8080❌协议 / 域名 / 端口 任一不同就是跨域2️⃣ 常见解决方案对比方案适用场景说明CORS后端配置生产环境后端加响应头JSONP老旧系统只支持 GETNginx 反向代理生产环境运维配置Vite Proxy​开发环境​✅ 前端自行解决开发环境用 Vite Proxy生产环境用 Nginx 或 CORS四、Vite Proxy 代理配置重点1️⃣ 基础配置// vite.config.ts export default defineConfig({ server: { proxy: { /api: { target: http://192.168.1.100:8080, changeOrigin: true } } } })效果前端请求/api/usersVite 转发到http://192.168.1.100:8080/api/users浏览器只和 localhost 通信不存在跨域2️⃣ 路径重写proxy: { /api: { target: http://192.168.1.100:8080, changeOrigin: true, rewrite: (path) path.replace(/^\/api/, ) } }请求/api/users→ 转发到http://.../users3️⃣ 多个代理目标proxy: { /api: { target: http://backend:8080, changeOrigin: true }, /upload: { target: http://file-server:9000, changeOrigin: true } }4️⃣ WebSocket 代理proxy: { /ws: { target: ws://localhost:3000, ws: true, changeOrigin: true } }五、生产环境的跨域处理1️⃣ Nginx 反向代理推荐 ✅server { listen 80; server_name example.com; location / { root /var/www/dist; try_files $uri $uri/ /index.html; } location /api/ { proxy_pass http://backend:8080/; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; } }前端和后端在同一域名下不存在跨域2️⃣ 后端 CORS 配置// Node.js / Express 示例 app.use(cors({ origin: [https://example.com], credentials: true }))六、环境变量安全注意事项⚠️ 重要前端环境变量是公开的VITE_API_BASE_URLhttps://api.example.com # ✅ 公开没问题 VITE_SECRET_KEYabc123 # ❌ 密钥不能放前端前端代码中不能放任何敏感信息数据库密码JWT 签名密钥私钥✅敏感信息只能放在后端七、部署时的常见问题❌ 问题 1刷新页面 404原因SPA 的路由是前端控制的服务器不认识/user这个路径解决Nginx 配置try_fileslocation / { try_files $uri $uri/ /index.html; }❌ 问题 2API 请求打到前端服务器原因生产环境baseURL配成了相对路径/api但没有代理解决生产环境用绝对路径 或 Nginx 代理❌ 问题 3环境变量不生效原因变量名没有VITE_前缀解决检查.env文件和变量名八、完整的 vite.config.ts 示例import { defineConfig, loadEnv } from vite import vue from vitejs/plugin-vue import path from path export default defineConfig(({ mode }) { // 加载对应模式的环境变量 const env loadEnv(mode, process.cwd()) return { plugins: [vue()], resolve: { alias: { : path.resolve(__dirname, src) } }, server: { port: 5173, open: true, proxy: { /api: { target: env.VITE_PROXY_TARGET || http://localhost:8080, changeOrigin: true, rewrite: (p) p.replace(/^\/api/, ) } } }, build: { outDir: dist, sourcemap: mode ! production, rollupOptions: { output: { chunkFileNames: assets/js/[name]-[hash].js, entryFileNames: assets/js/[name]-[hash].js, assetFileNames: assets/[ext]/[name]-[hash].[ext] } } } } })九、面试高频问答Q1Vite 中环境变量为什么必须以 VITE_ 开头防止意外将敏感环境变量暴露到客户端代码中。Q2Vite Proxy 在生产环境能用吗不能Vite Proxy 只在开发服务器生效生产环境用 Nginx。Q3SPA 部署后刷新 404 怎么解决服务器配置 fallback 到 index.htmlNginx 的 try_files。十、总结架构级.env文件管理不同环境的配置VITE_前缀控制变量暴露Vite Proxy 解决开发环境跨域生产环境用 Nginx 反向代理前端环境变量是公开的不能放敏感信息 下期预告第 21 篇Vue3 性能优化九大策略