Have you ever struggled with Webpack splitChunks? It’s not breaking and reusing repetitive modules?

Let me tell you a story

The Developer, the Component Library, the Webpack:

I’m building a library with several components and I’m breaking them as multiple entries: if the user wants to use a <Button> it will be requested only its code, nothing more.

Checking the final results with Webpack Bundle Analyzer, I just realized several common modules repeating between all entries! Imports these components, will cause the inclusion of repeated code, maybe more than twice!

So tried with splitChunks configuration to make this common code be reused between them. No success at all. Then from the docs, I realized that each entry is a bundle itself and has its own “parent-child relationship in the internal webpack graph”, in a way that the repeated modules are happening because they’re on different “trees”, on each bundle.

“The problem may be because I have multiple entries! Webpack splitChunks will work only inside a bundle itself.”

So I thought, how can I force webpack to reuse a certain module between entries? Looking for some threads, found these two fantastic plugins: DllPlugin and DllReferencePlugin.

DllPlugin for the rescue!

I’ll use an example to simplify the things: let’s say you have your UI library (can be any other type too, just for simplicity) and it’s exposing two different components: Component-A and Component-B.

Then there’s common code being used between them, and whoever uses your library, will pay twice for certain common code. Ok, nothing new, you already saw this situation in the previous section.

With a simple webpack config:

You end up with this:

Check the live version here

There’s a big common.js in both components code! But hey, we just saw splitChunks will not be effective and we need to use DllPlugin and DllReferencePlugin.

We can build the config for creating the DLL:

This will make it generate the entry and a manifest.json containing important information about the DLL.

Now for the UI lib configuration, we change a little to reference the DLL:

You’ll end up with this:

Check the live version here

Now both components have only references to common.js (which measured, costs only 272 Bytes!)

“Why not using the multicompiler?”

The DLL must be compiled before the main project, as it will require the manifest.json and the DLL code to be there. You can solve this with the Node API + compilation hooks, but for the sake of simplicity, I didn’t want to use this to make this example.

DllPlugin Use Cases

Please to go full DLL around your project, use Webpack Bundle Analyzer to check the common code that costs too much to your user, like for instance, static i18n values, non-external libraries, or anything that repeats and is too big in your point of view. Common sense is the key to maintain your project lean and control the complexity of your architecture.