3

I use cra, and pass variables through the .env file. During the building process webpack replace the references to the process.env... with the values form the .env file and chunk contains 'hardcoded' values as a result, that's why I have to rebuild application every time to deploy it to the different environments.

How can I configurate webpack in such a way to don't rebuild whole app just to change environment variables?

juror
  • 31
  • 3
  • No, as you say, during building and packing the original values are replaced with values from the respective env file. That's the whole point of it. The only thing you can do is, to include all your different configs into your chunk. But still, you would have somehow to define which one of them to use. A clumsy approach would be to define some constant which determines the environment. And if you want to change the environment, update that constant with search and replace. But as I said. Thats very *hacky* and *clumsy*. I do not recommend this. – derpirscher Apr 01 '21 at 13:52
  • 1
    Does this post help? [Using server environment variables into frontend at client side](https://stackoverflow.com/q/66883900/2873538) – Ajeet Shah Apr 01 '21 at 14:00
  • Actually had an idea to put variables to the json file (don't use .env) and a get access to it through the _window_ global object, because even inside of the chunk we still have a **references** to its values. Than we can change the values of this json file and it'll be picked up dynamically. But the issue here is to configurate webpack in such a way to create this json an to populate it in the pipeline. And I'm not sure that it's ok to store env variables in the window. – juror Apr 01 '21 at 14:13
  • 1
    @juror If you want to change the env vars without recreating a "build" with `npm run build` command, I think the easiest and (perhaps) the only way is to use "server-side variables" as mentioned in https://stackoverflow.com/q/66883900 – Ajeet Shah Apr 01 '21 at 14:27

1 Answers1

2

Your built React app is just a bunch of static JavaScript files. If you want to vary what gets baked into your static bundle, you need to rebuild the app.

If you want to dynamically load in environment variables, you'll need to render your JavaScript on the server.

Alternatively, build the JavaScript bundle as part of a deployment pipeline so it's automated for you. Tools like Netlify do this for you, and allow you to configure the env vars to pass in.

trh88
  • 612
  • 8
  • 22