Hello Fellow developer in this blog we are going to discuss another issue of how to make out enviroment variables dynamic.
Have you ever needed to deploy React application to multiple environments?
If you’ve ever had to do above, then scenario like this may sound familiar to you: You have an existing build file, you wish to change some environment variable, then re-deploy it to new environment.
Unfortunately, you soon realize that environment variable have been hard-coded within build file. This means that you cannot change environment variables without re-building.
So to fix this problem an ideal solution has been found that solves following problems as well
- React files Does not require a rebuild
- There are Minimal changes in code
- It Allows synchronous access of environment variable
- It is Easy to integrate with your current workflow
- It is Simple and straightforward
react-inject-env: tool that allows you to modify environment variables after static file has been built
Short and simple explanation is that it creates an env.js
file in /public
folder. File is then executed at start and variables are loaded into window
object.
Steps to use it are:
1.Install react-inject-env in your app
npm install react-inject-env --save-dev yarn add react-inject-env --dev
2. Add following code to your index.html
<script src='/env.js'></script>
3. Create new file called env.js
and copy following code:
export const env = { ...process.env, ...window['env'] }
4.Replace all instances of process.env
with newly created env
variable like example given below
import { env } from './env' export const App = () => { return ( <div style={{backgroundColor: env.REACT_APP_COLOR}}> <span>{env.REACT_APP_MAIN_TEXT}</span> </div> ) }
5. Build your static files using npm run build
/ react-scripts build
/ whatever our build script is.
6. Set our environment variables using following command:
[env variables] npx react-inject-env set # with a black background REACT_APP_COLOR=black REACT_APP_MAIN_TEXT="Black Background" npx react-inject-env set # with a blue background REACT_APP_COLOR=blue REACT_APP_MAIN_TEXT="Blue Background" npx react-inject-env set # for windows set REACT_APP_COLOR=navy&& set REACT_APP_MAIN_TEXT=Navy Background&& npx react-inject-env set
7. Open build/env.js
to verify that our variable is present.
And thats it you are done here!!