Make Webpack exit on compilation errors

Alfred Yang
finnovate.io
Published in
2 min readApr 20, 2020
Photo by jesse ramirez on Unsplash

Webpack is a great tool for bundling JavaScript, but one quirk I noticed ever since working with Webpack 1.x is that it doesn’t exit its own process by default on compilation errors.

This behavior is fine when running Webpack on development machines as we can hit Ctrl-c (or Cmd-c) to kill the process, but it gets quite annoying in a continuous integration pipeline. Upon seeing an error, Webpack causes the pipeline process to hang, and developers are left wondering why the build hasn’t finished in over an hour.

To instruct Webpack to exit on compilation errors, we introduced a simple custom plugin into our webpack.config.js.

For Webpack V4:

const webpackConfig = {...}; // our normal Webpack configwebpackConfig.plugins.push(function () {
this.hooks.done.tapAsync('done', function (stats, callback) {
if (stats.compilation.errors.length > 0) {
throw new Error(
stats.compilation.errors.map(err => err.message || err)
);
}
callback();
});
});
...webpack(webpackConfig);

The above code creates a plugin that throws an error when Webpack compilation finishes with one or more errors. This will cause the Webpack process to exit.

The .hooks API was recently introduced in Webpack v4, but you can introduce the same behavior with prior versions of Webpack.

For Webpack V3 or older:

const webpackConfig = {...}; // our normal Webpack configwebpackConfig.plugins.push(function () {
this.plugin('done', function (stats) {
if (stats.compilation.errors.length) {
throw new Error(
stats.compilation.errors.map(err => err.message || err));
}
});}
);
...webpack(webpackConfig);

Note that the .plugin function is deprecated in Webpack V4, so you will get a ‘Tapable.plugin is deprecated’ error if you attempt to use the V3 example with Webpack V4.

Now Webpack will exit as one may expect on compilation errors.

Finnovate.io is a technology company focused on helping organizations build unique digital experiences on web, mobile and blockchain. Finnovate.io offers development services, training, consulting, as well as a platform that rapidly turn paper based content into interactive experiences.

--

--

Alfred Yang
finnovate.io

Alfred is the founder of https://finnovate.io, a company that focuses on helping organizations build unique digital experiences on web, mobile and blockchain.