Is it possible to override the variables inside .env on run or build?
Content of the .env file
REACT_APP_REGIONALIZED_BASE_API_URL=http://hello-default.net
Command script in package.json
"scripts": {
"start:production": "env-cmd -f .env react-scripts start",
}
Sample start command executed in terminal or even in ci/cd pipeline where you have instances based on regions
REACT_APP_REGIONALIZED_BASE_API_URL=http://hello-eu.net yarn start:production
So, instead of having a build with api url http://hello-default.net
, it should have http://hello-eu.net
CodePudding user response:
Yes, there is a way you can do that. You can do that with a package called runtime-env-cra
.
The runtime-env-cra
package was meant to be used in Docker or VM based environments, where you have full control over how your application will start. Sadly, runtime-env-cra
can not be used if you are using S3 or another static file serving solution.
You just have to add the following to public/index.html
inside the <head>
tag
<!-- Runtime environment variables -->
<script src="%PUBLIC_URL%/runtime-env.js"></script>
Modify your start
script to the following in your package.json
:
"scripts": {
"start": "NODE_ENV=development runtime-env-cra --config-name=./public/runtime-env.js && react-scripts start",
}
But be careful, If you are using windows
then you need to use cross-env
"scripts": {
"start": "cross-env NODE_ENV=development runtime-env-cra --config-name=./public/runtime-env.js && react-scripts start",
}
The script parses everything based on your .env
file and adds it to window.__RUNTIME_CONFIG__
. If you pass NODE_ENV=development
for the script, it will use the values from your .env, but if you provide anything else than development
or nothing for NODE_ENV
it will parse environment variables from process.env
. This way you can dynamically set your environment variables in production/staging environments without the need to rebuild your project.
CodePudding user response:
Sharing the [alternative] solution I discovered. Just need to add --no-override
argument. This will prevent replacing of the already set variable. Also applicable with multiple env files.
"scripts": {
"start:production": "env-cmd --no-override -f .env react-scripts start",
}