Advanced splitting of multi-entry project using webpack
A slightly more advanced usage of CommonsChunkPlugin.
If you have a multi-entry project, most likely it can be characterized by this cool Venn Easter Egg Diagram I just put together.
Besides your own custom modules there probably are some vendor dependencies. It is very likely that in a multi-entry setup you have some modules that are used across many entries. At least that is how my work tends to organize itself.
My goal is to have bundles that are very well suited for long term caching. This is where webpack is very handy. Webpack has a built in content hashing functionality so it is very easy to create unique file names for target bundles that can be cached indefinitely.
First step to achieve my goal is to split off modules that are used in all entries. Webpack provides a powerful CommonsChunkPlugin that allows extracting modules that are commonly used in multiple entries.
Lets say you have the following two entries:
To make webpack do the work for me, I just have to configure the pluging like this:
This will create a 3rd chunk named “common”.
While this is a step in the right direction, this is not the finish line yet. You may have noticed that my cool visualization that I am very proud of contains six red dots not three. We have not yet handled vendor dependencies.
If we try to characterize custom modules and vendor modules, it becomes clear that they have totally different iteration cycles. Custom modules tend to change frequently while vendor modules tend to stay exactly the same for a long time.
In the current setup, every time a custom module is changed it takes some vendor dependencies along. It would be nice if CommonsChunkPlugin could do this for me.
“If I’ve learned anything about webpack, the answer is always yes. It’s just a matter of how :)”
I took me a long time to extract this knowledge from webpack docs and examples. Nevertheless, here it is:
🏁Now we are at the finish line!
This webpack setup splits my two entries in six chunks. Half of them are vendor dependencies that change less frequently than the other half. Each page can now use two common chunks and two page-specific chunks.
You can play around with a working example here: https://github.com/klavs/advanced-webpack-commons-chunk-example.
That’s it! The final webpack configuration is much simpler than I anticipated. Webpack only needs to know the entry points and in which directory vendor modules are located. Everything else happens automatically.
As I already mentioned, It took a lot of time to get this working as expected. Please leave a comment about your experience using CommonsChunkPlugin! Am I doing it right? Am I doing it wrong?