如何为React App设置env变量? [英] How to setup the env variable for the react app?
问题描述
我的react应用程序在http://localhost:3000上运行,我想为不同的环境开发,生产,暂存和本地环境设置env变量.
My react app is running on http://localhost:3000 and I wanted to setup the env variable for the different environment development, production, staging and local.
我在不同环境下的应用URL是(我在嘲笑我的URL)
my react app url for different environment are(I am mocking my urls)
local = http://localhost:3000
development = http://react.developmet.com
production = http://react.production.com
stage = http://react.stage.com
寻找解决方案,如何为不同的环境设置环境变量.
looking for a solution how i can setup the env var for different environment.
将我的方法添加到刚刚想知道的这种方法的优缺点中.
Adding my approach to the same thing just wanted to know is this approach is good or not.
以及如何在暂存环境中实现相同目标
and how I can achieve same for staging environment
我已经创建了一个 environment.js 文件.
I have created an environment.js file.
let BASE_URL = http://localhost:3000
//check for environment
if (process.env.REACT_APP_ENV = "development") {
BASE_URL = "http://react.developmet.com"
}
if (process.env.REACT_APP_ENV = "production") {
BASE_URL = "http://react.production.com"
}
export {BASE_URL}
并更新了我的运行脚本
"scripts": {
"dev":"REACT_APP_ENV=development npm start",
"prod":"REACT_APP_ENV=productionnpm start",
"build:dev":"REACT_APP_ENV=development npm run-script build",
"build:prod":"REACT_APP_ENV=production npm run-script build",
}
推荐答案
您可以使用 env-cmd 来管理多个 env
文件的构建:
You can use env-cmd to manage your build for multiple env
files:
yarn add env-cmd -D
创建环境文件
- 在根项目级别创建一个文件夹
envs
- 创建
.env
文件(您需要的数量)
例如 envs/.env.dev
, envs/.env.prod
, envs/.env.staging
等
REACT_APP_API_HOST=http://my-prod-api.example.com
REACT_APP_ANY_OTHER_VAR=some_value
在package.json文件中配置脚本:
"scripts": {
"start": "react-scripts start",
"eject": "react-scripts eject",
"dev": "env-cmd -f envs/.env.dev react-scripts build",
"prod": "env-cmd -f envs/.env.prod react-scripts build",
"staging": "env-cmd -f envs/.env.staging react-scripts build",
},
进行构建:
$ yarn dev // to make build for dev env
$ yarn prod // to make build for prod env
$ yarn staging // to make build for staging env
PS:您也可以使用 npm
命令.我仅将 yarn
用于示例.
PS: You can use npm
commands as well. I used yarn
only for example purpose.
这篇关于如何为React App设置env变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!