With ReactJS 18.2.0
using env-cmd
library,
For more complex projects, a .env-cmdrc file can be defined in the
root directory and supports as many environments as you want. Simply
use the -e flag and provide which environments you wish to use from
the .env-cmdrc file. Using multiple environment names will merge the
environment variables together.
In simple, if you want the all environment declaration with similar variable keys in one file, like development, dev1, staging, test, qa, test, production, etc., so if you use REACT_APP_API_URL
so based on the environment, it would serve you the value.
Using env-cmd
10.1.0 library (which has been not updated since 3 years as on date, but popular) could achieve using .rc
file OR .env-cmdrc
I've used using .env-cmdrc
(I've not used like .env-cmdrc.json
) putting inside the project root directory, means parallel to package.json
file.
Now let's deep inside the .env-cmdrc
{
"development": {
"README": "Variable Keys starting with REACT_APP_* will be visible to process.env with ReactJS 18 Scripts, like this README will not get reflect there inside app after process.env, because it won't started with REACT_APP, this is the way because project got started from create-react-app, hence this is the reason.",
"REACT_APP_ENV": "development",
"REACT_APP_URL": "http://localhost:3000/",
"REACT_APP_API_URL": "https://something-a.onrender.com/thedb"
},
"test": {
"REACT_APP_ENV": "test",
"REACT_APP_URL": "http://localhost:3000/",
"REACT_APP_API_URL": "https://something-a.onrender.com/thedb"
},
"production": {
"REACT_APP_ENV": "production",
"REACT_APP_URL": "https://somethingdb.netlify.app/",
"REACT_APP_API_URL": "https://something-a.onrender.com/thedb"
}
}
Note: Variable Keys starting with REACT_APP_*
will be visible to process.env
with ReactJS
18 Scripts, like this README will not get reflect there inside app after process.env, because it won't started with REACT_APP
, this is the way because project got started from create-react-app
, hence this is the reason.
Now, let's move to package.json
file.
"scripts": {
"start": "env-cmd --environments development react-scripts start",
"build": "env-cmd --environments production react-scripts build",
"test": "env-cmd --environments test react-scripts test",
"eject": "react-scripts eject"
},
Now, if somewhere I want to get value variable key REACT_APP_API_URL
based on whatever environment, simply use process.env.REACT_APP_API_URL
the trick is that every variable must starts with REACT_APP
and to start the project in development, I write in vscode
terminal npm start
I hope it would clear many of the peoples doubt & issue.