Webpacking environment variables

Rafael Camargo
Mar 8, 2018 · 2 min read
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.

 — environments/
 — — development.js
 — — production.js

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

export default {
 API_BASE_URL: 'http://api.myproject.com/v1'

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:

"resolve": {
  "alias": {
    "@environment$": `${__dirname}/environments/${env}.js`

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:

const argv = require('yargs').argv;
const env = argv.env || 'development';

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:

import ENV from '@environment';
import axios from 'axios';axios.get('${ENV.API_BASE_URL}/my/api/endpoint');

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

BONUS 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:

 webpackConfig = require('./webpack.config.js');module.exports = {
 "moduleNameMapper": webpackConfig.resolve.alias

If you work in a company that is hunting for excellent Javascript developers, try https://hiphunt.com. Hiphunt evaluates thousands of developers and get them ordered in front of you.

Rafael Camargo

Written by

Dedicating myself to https://hiphunt.com . Driven by https://theunseriousmanifest.org. Open sourcer at https://glorious.codes. More in https://rafaelcamargo.com