React多环境配置(create-react-app)
通过create-react-app创建的项目,自身支持多环境配置
详见: https://create-react-app.dev/docs/adding-custom-environment-variables/
注意
所有环境变量必须以
REACT_APP_开头,env中只会保留NODE_ENV和REACT_APP_*的环境变量You must create custom environment variables beginning with REACT_APP_. Any other variables except NODE_ENV will be ignored
使用
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",
…,
}
设置环境变量
在运行项目前
SET,环境变量必须以REACT_APP_开头通过配置文件
在项目根目录下建立env配置文件
优先级由低到高排序
文件名 功能 .env 默认 .env.local 当运行环境不是test时,覆盖.env的设置 .env.development.env.test.env.production 覆盖各自环境的设置 .env.development.local.env.test.local.env.production.local 覆盖上方的设置 配置文件格式为
1
2
3REACT_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为例
在HTML中使用
1
<p>%REACT_APP_ABC%</p>
在Node中使用
可通过
process.env获取1
2let abc:string|undefined = process.env.REACT_APP_ABC
//abc的值为'abc'