Application Configuration with Webpack: Update

Matt McLaughlin
Matt McLaugh
Published in
2 min readFeb 13, 2017

--

In a previous article, I outlined a method for application configuration in Webpack using the alias directive. The alias approach is ideal because it requires no extra libraries and is declared explicitly in Webpack configuration. However, because the alias happens in Webpack, it is not available when code gets executed by test runners such as Mocha.

Webpack aliases work by associating a desired import path to a file in a different location. For environment configuration this allows us to map different config files to the same import path depending on the environment.

Because the project uses Babel to load .js files in both Webpack and Mocha, we can get around this limitation by using the babel-plugin-webpack-alias library. Now when Babel runs, it will scan the supplied Webpack configuration and recreate any aliases.

Example .babelrc with babel-plugin-webpack-alias plugin

You may even want to load a test specific Webpack configuration file. Then run you tests with the babel compiler as usual.

NODE_ENV=test mocha --compilers js:babel-register --recursive

The downside to this method is importing yet another library and where the configuration occurs isn’t very intuitive. Thankfully, the library is only needed for testing and won’t add to the overhead of a production build.

Because the configuration happens in Babel (in the hidden .babelrc no less), it’s not explicitly clear how the configuration is translated from application configuration in webpack to our test suite in mocha. A little documentation can solve the problem, but it’s not the kind of pattern to get in the habit of using.

--

--

@mattmclaugh Professional problem solver and unceasing builder. A bicycle powered full stack developer focused on teams, architecture, and customer experience.