How To Handle Multiple Environments In React App
Solution 1:
i think you should use environment variables and create an .env file and its seprate from your project.
for more information you can react docs about environment variables
or you can use npm scripts variables
I hope it was useful.
Solution 2:
In case you are with create-react-app, and only need local and production environment go with Adding Custom Environment Variables build-in feature. Otherwise, a useful alternative is env-cmd.
Install env-cmd, as a development dependency:
npm i -D env-cmd
Add .env file (at project root, same for all environments):
REACT_APP_API_ENDPOINT = https://default.example.com
Add .env.qa file:
REACT_APP_API_ENDPOINT = https://qa.example.com
Add .env.staging file:
REACT_APP_API_ENDPOINT = https://stage.example.com
Add .env.production file:
REACT_APP_API_ENDPOINT = https://production.example.com
Update package.json
{
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"build:qa": "env-cmd -f .env.qa npm run-script build",
"build:staging": "env-cmd -f .env.staging npm run-script build",
}
}
Note that default start and build create-react-app commands are using .env and .env.production respectively, and have no need of env-cmd.
Ready to use in our code
const baseUrl = process.env.REACT_APP_API_BASE_URL;
And, we also can use env-cmd for start command at development environment.
Post a Comment for "How To Handle Multiple Environments In React App"