通过create-react-app创建的项目,自身支持多环境配置

详见: https://create-react-app.dev/docs/adding-custom-environment-variables/

注意

  1. 所有环境变量必须以REACT_APP_开头,env中只会保留NODE_ENVREACT_APP_*的环境变量

    You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored

  2. 使用react-scripts启动项目时,设置NODE_ENV是无效的

    When you run npm start, it is always equal to ‘development’, when you run npm test it is always equal to ‘test’, and when you run npm run build to make a production bundle, it is always equal to ‘production’. You cannot override NODE_ENV manually.

    命令 NODE_ENV
    start development
    test test
    build production

    以下方式设置的NODE_ENV是无效的

    1
    2
    3
    4
    "scripts": {
    "start": "SET NODE_ENV="production" react-scripts start",
    …,
    }

设置环境变量

  1. 在运行项目前SET,环境变量必须以REACT_APP_开头

  2. 通过配置文件

    https://create-react-app.dev/docs/adding-custom-environment-variables/#what-other-env-files-can-be-used

    在项目根目录下建立env配置文件

    优先级由低到高排序

    文件名 功能
    .env 默认
    .env.local 当运行环境不是test时,覆盖.env的设置
    .env.development
    .env.test
    .env.production
    覆盖各自环境的设置
    .env.development.local
    .env.test.local
    .env.production.local
    覆盖上方的设置

    配置文件格式为

    1
    2
    3
    REACT_APP_KEY1=value1
    REACT_APP_KEY2=value2

    如: REACT_APP_ABC=abc

    各环境变量也可互相调用,详见 https://github.com/motdotla/dotenv-expand

    如: REACT_APP_KEY3=${REACT_APP_KEY1}def

使用

此处以环境变量REACT_APP_ABC=abc为例

  1. 在HTML中使用

    1
    <p>%REACT_APP_ABC%</p>
  2. 在Node中使用

    可通过process.env获取

    1
    2
    let abc:string|undefined = process.env.REACT_APP_ABC
    //abc的值为'abc'