Exclude node_modules with Webpack
Posted 15 September 2023
When using Webpack dependencies in node_modules
will be included in the build output by default. This is useful behaviour when you're building a bundle for a web app, but for some use cases such as using Webpack to build a library or Node application you may want to exclude these dependencies so they are loaded from node_modules
at runtime.
The Webpack externals
options allows you to specify dependencies to exclude from the build. If you want to exclude all dependencies the webpack-node-externals provides a simple way to build an externals
function that excludes all dependencies in your project's node_modules
directory.
// webpack.config.js
const nodeExternals = require('webpack-node-externals');
module.exports = {
...
// ignore all modules in node_modules
externals: [nodeExternals()],
...
};
Our use case
At Mintel we have a collection of frontend libraries that make up our design system. We use Storybook for local development and ran into a few cases where differences between the library and Storybook build process meant that issues were missed by engineers as they developed changes.
To catch these issues sooner our platform team decided to align the build process of the library and Storybook, using the same Webpack configuration to build both the Storybook and the published library.
However, this change led to increased bundle sizes for applications consuming these libraries. The libraries would package up all dependencies in the build, causing duplication in cases of shared dependencies. By excluding dependencies from the Webpack build we were able to hoist dependency resolution up to consuming project again and let the package manager do its job.