Webpacking environment variables

Rafael Camargo
Mar 8, 2018 · 2 min read
Image for post
Image for post
Using alias in Webpack configuration to handle environment vars in your application modules.

This is a complement to a previous post about bundling environment variables using Gulp.

Keeping with the same expectation of maintaining a simple, easy to understand and crystal clear way to manage environment variables in the browser without having to make any trick or write unnecessary code, I show below how to achieve that same result using now Webpack.

The very first step is still creating a folder in your project to store a Javascript file for each environment.

Those files should export the environment variables using the ES6 syntax.
For example:

In your Webpack configuration file, you should now use an alias for the environment module to be used by your application modules. Inside the configuration key “resolve”, declare the environment module alias:

The name of the environment file continues to be variable like in the Gulpfile, you should pass that value to your NPM script using the env flag.
Make sure you have required the yargs package in your configuration file:

Now, all you have to do is to import the environment module in any module of your application that needs to use some environment variable:

Have you found a better way of webpacking your environment variables? Please, let me know.

This approach may broke your unit tests, since they won’t resolve the environment module properly. So, if you are using Jest as your test runner (and I strongly recommend it), you easily solve this issue with just one line in your Jest configuration file:

Are you struggling to configure and use StorybookJS? You have an alternative. It’s Pitsby. No rules. No loaders. No regex. Ship your docs with a couple of super simple declarations.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store