基于Node/Vite实现一次构建多环境运行的方案咨询
实现Vite项目一次构建多环境运行的可行方案
要实现Vite项目一次构建、多环境运行,核心是把环境变量的读取时机从构建阶段推迟到运行阶段,避免构建时固化环境配置。以下是几个落地性强的方案:
方案1:运行时读取全局注入的环境变量
这是最直接的方式,通过在部署阶段向全局window对象注入环境变量,前端代码在运行时直接读取:
- 在项目根目录的
index.html中添加占位符脚本:
<script> // 定义全局环境变量占位符,构建时Vite不会替换这些内容 window.__APP_ENV__ = "%APP_ENV%"; window.__API_BASE_URL__ = "%API_BASE_URL%"; </script>
- 执行常规Vite构建:
npm run build
部署时用脚本替换占位符:
- 开发环境部署脚本(Linux/macOS):
sed -i 's/%APP_ENV%/dev/g' dist/index.html sed -i 's/%API_BASE_URL%/https://dev-api.example.com/g' dist/index.html - 生产环境部署脚本(Linux/macOS):
sed -i 's/%APP_ENV%/prod/g' dist/index.html sed -i 's/%API_BASE_URL%/https://prod-api.example.com/g' dist/index.html - Windows环境可改用PowerShell的替换命令:
(Get-Content dist/index.html) -replace '%APP_ENV%', 'dev' | Set-Content dist/index.html
- 开发环境部署脚本(Linux/macOS):
前端业务代码中直接使用:
const currentEnv = window.__APP_ENV__; const apiUrl = window.__API_BASE_URL__; if (currentEnv === 'dev') { console.log('运行在开发环境'); } else { console.log('运行在生产环境'); }
方案2:静态配置文件+部署时替换
如果不想修改index.html,可以单独维护一个配置文件,利用Vite对public目录的复制特性实现:
- 在
public目录下创建config.js:
window.APP_CONFIG = { env: "%APP_ENV%", apiBaseUrl: "%API_BASE_URL%", timeout: 10000 };
构建后,
dist目录会保留这个config.js,部署时用方案1的替换脚本修改该文件即可。前端代码中读取配置:
const { env, apiBaseUrl } = window.APP_CONFIG;
方案3:容器化部署(Docker)动态注入
如果用Docker部署,可以在容器启动时动态传入环境变量,自动替换占位符:
index.html中保留占位符(同方案1)。编写
Dockerfile:
FROM nginx:alpine # 复制构建产物到Nginx目录 COPY dist /usr/share/nginx/html # 复制启动脚本 COPY entrypoint.sh /entrypoint.sh RUN chmod +x /entrypoint.sh # 执行启动脚本后启动Nginx ENTRYPOINT ["/entrypoint.sh"]
- 编写
entrypoint.sh启动脚本:
#!/bin/sh # 替换index.html中的环境变量占位符 sed -i "s/%APP_ENV%/$APP_ENV/g" /usr/share/nginx/html/index.html sed -i "s/%API_BASE_URL%/$API_BASE_URL/g" /usr/share/nginx/html/index.html # 启动Nginx nginx -g 'daemon off;'
- 启动容器时传入环境变量:
# 开发环境 docker run -e APP_ENV=dev -e API_BASE_URL=https://dev-api.example.com -p 8080:80 your-image-name # 生产环境 docker run -e APP_ENV=prod -e API_BASE_URL=https://prod-api.example.com -p 80:80 your-image-name
关键注意事项
- 不要直接使用Vite的
import.meta.env存储需要切换的环境变量,这类变量是构建时注入的,会被固化到JS产物中,无法在运行时修改。 - 如果Vite配置文件(如
vite.config.js)中需要环境变量(比如开发代理),这部分仍属于构建时配置,不影响业务代码的运行时切换逻辑。 - 替换占位符时,要确保部署环境的脚本工具兼容(比如Windows用PowerShell,Linux/macOS用bash)。
内容的提问来源于stack exchange,提问作者edouard
相关产品推荐
相关产品推荐

