背景
前端项目从项目开发到上线,一般存在开发环境、测试环境、预发布环境、生产环境,每一个环境的配置大不相同,如何方便规范的管理不同环境的配置是一个需要解决的问题。相对于运行时改变环境变量的方式,运用打包模式来解决这个问题更加优雅。
示例
- Webpack
使用内置 DefinePlugin 插件
new webpack.DefinePlugin({
BASEURL: 'api.dev.com',
});
new webpack.DefinePlugin({
BASEURL: 'api.prod.com',
});
{
"name": "zmn-test",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "webpack-dev-server --open --config webpack.dev.js",
"build": "webpack build --config webpack.prod.js",
"build:test": "webpack build --config webpack.dev.js"
},
}
//全局使用
console.log(BASEURL)
Vue Cli
VUE_APP_BASEURL=api.dev.com
VUE_APP_BASEURL=api.prod.com
{
"name": "zmn-test",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "vue-cli-service serve --mode development",
"build": "vue-cli-service build --mode production",
"build:test": "vue-cli-service build --mode development"
},
}
//全局使用
console.log(process.env.VUE_APP_BASEURL)
Vite
VITE_APP_BASEURL=api.dev.com
VITE_APP_BASEURL=api.prod.com
{
"name": "zmn-test",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "vite --mode development",
"build": "vite build --mode production",
"build:test": "vite build --mode development"
},
}
console.log(import.meta.env.VITE_BASEURL);
Create-React-App
REACT_APP_BASEURL=api.dev.com
REACT_APP_BASEURL=api.prod.com
// create-react-app 默认支持 development production 环境变量,需要借助 dotenv-cli 库,注入其他环境变量,如预发布环境
{
"name": "zmn-test",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "react-scripts start",
"build": "dotenv -e .env.production react-scripts build",
"build:dev": "dotenv -e .env.development react-scripts build",
},
}
附录
DefinePlugin 源码: https://github1s.com/webpack/webpack/blob/HEAD/lib/DefinePlugin.js
Vue Cli 源码:https://github1s.com/vuejs/vue-cli/blob/HEAD/packages/@vue/cli-service/lib/util/resolveClientEnv.js
Vite 源码: https://github1s.com/vitejs/vite/blob/HEAD/packages/vite/src/node/plugins/define.ts
Create-React-App 源码: https://github1s.com/facebook/create-react-app/blob/main/packages/react-scripts/config/env.js