How to setup a staging environment when using webpack

Apparently after investigation, one cannot simply just specify a different environment variable other than production and actually the reason makes sense.

Reason why it is not straightforward to configure a staging environment

So, the reason is plain and simple. React does optimizations for production environment and if you used anything other than that it would simply not make sense.

Note that it makes sense in a React project but in any other frontend library/framework it might not.

Show me the "workaround"

Having said that, it would be "stupid" to force only a production environment when you might have a staging environment for example with different configuration details, client-side API keys et cetera.

Gladly, webpack provides a way to define and pass your own ENV variables as shown below

module . exports = env => { return { mode : 'production' , plugins : [ new webpack . DefinePlugin ( { 'process.env' : { TARGET_ENV : JSON . stringify ( env . TARGET_ENV ) , } , } ) , ] , } }

And to pass the TARGET_ENV variable

webpack --config webpack.config.js --env.TARGET_ENV=staging

Now in your app instead of checking with process.env.NODE_ENV === 'staging' you can check using process.env.TARGET_ENV === 'staging' .

Conclusion

This way you can have the optimizations done by React when in production env and handle the rest of the environment using TARGET_ENV accordingly.

P.S if you know a better way, feel free to share in the comments section below :)