背景

前端项目从项目开发到上线,一般存在开发环境、测试环境、预发布环境、生产环境,每一个环境的配置大不相同,如何方便规范的管理不同环境的配置是一个需要解决的问题。相对于运行时改变环境变量的方式,运用打包模式来解决这个问题更加优雅。

示例

  1. Webpack

使用内置 DefinePlugin 插件

  1. new webpack.DefinePlugin({
  2. BASEURL: 'api.dev.com',
  3. });
  1. new webpack.DefinePlugin({
  2. BASEURL: 'api.prod.com',
  3. });
  1. {
  2. "name": "zmn-test",
  3. "version": "0.1.0",
  4. "private": true,
  5. "scripts": {
  6. "dev": "webpack-dev-server --open --config webpack.dev.js",
  7. "build": "webpack build --config webpack.prod.js",
  8. "build:test": "webpack build --config webpack.dev.js"
  9. },
  10. }
  1. //全局使用
  2. console.log(BASEURL)
  1. Vue Cli

    1. VUE_APP_BASEURL=api.dev.com
    1. VUE_APP_BASEURL=api.prod.com
    1. {
    2. "name": "zmn-test",
    3. "version": "0.1.0",
    4. "private": true,
    5. "scripts": {
    6. "dev": "vue-cli-service serve --mode development",
    7. "build": "vue-cli-service build --mode production",
    8. "build:test": "vue-cli-service build --mode development"
    9. },
    10. }
    1. //全局使用
    2. console.log(process.env.VUE_APP_BASEURL)
  2. Vite

    1. VITE_APP_BASEURL=api.dev.com
    1. VITE_APP_BASEURL=api.prod.com
    1. {
    2. "name": "zmn-test",
    3. "version": "0.1.0",
    4. "private": true,
    5. "scripts": {
    6. "dev": "vite --mode development",
    7. "build": "vite build --mode production",
    8. "build:test": "vite build --mode development"
    9. },
    10. }
    1. console.log(import.meta.env.VITE_BASEURL);
  3. Create-React-App

    1. REACT_APP_BASEURL=api.dev.com
    1. REACT_APP_BASEURL=api.prod.com
    1. // create-react-app 默认支持 development production 环境变量,需要借助 dotenv-cli 库,注入其他环境变量,如预发布环境
    2. {
    3. "name": "zmn-test",
    4. "version": "0.1.0",
    5. "private": true,
    6. "scripts": {
    7. "dev": "react-scripts start",
    8. "build": "dotenv -e .env.production react-scripts build",
    9. "build:dev": "dotenv -e .env.development react-scripts build",
    10. },
    11. }

    附录

    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