Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to edit .env file after build completed reactjs

i had build react app web page with custom environment variables
the problem is when i build the script and change the .env variables no thing change in the website !

.env file :

REACT_APP_SITENAME=TheSiteName App

like image 458
Tawfek Mohammed Avatar asked Dec 02 '22 10:12

Tawfek Mohammed


2 Answers

After building a react app all code is static and can't be changed. I think the only solution to send some dynamic data to your react app is to either create a special file per system you running your app on and load this directly inside the index.html or create the content of this file on the fly. So when you're using create-react-app in public/index.html add something like this:

<head>
...
<script src="https://www.example.com/envconfig.js" type="text/javascript">
</script>
...
</head>

This file should contain the environmental config, e.g.:

window.globalConfig = {
    siteName: "The Sitename App"
}

The file can also be created on the fly by PHP, Java or any other backend service. Just make sure to answer as valid Javascript.

And in your React app at index.js, App.js or anywhere you can access this variable as it is global:

   const appConfig = window.globalConfig || { siteName: process.env.REACT_APP_SITENAME}   

With this you've got an fallback to the static env config if globalConfig is not available, likely in development. Now you can use appConfig in any way and provide it via redux, context or property to your components.

Last thing to mention, you have to make sure that the config-file is loaded before executing all the React code. So the file should be loaded before all the created React files.

like image 151
Auskennfuchs Avatar answered Dec 25 '22 11:12

Auskennfuchs


Quote from the docs:

The environment variables are embedded during the build time.

It isn't possible to apply environment changes as runtime.

Reference

Here is an example of how to use the environment at runtime:

CodeSandbox

like image 34
Randy Casburn Avatar answered Dec 25 '22 11:12

Randy Casburn