Moving shared modules into common chunks

I’m working on converting a website from a RequireJS to a Webpack-based workflow, and I’m having trouble with the way that the CommonsChunkPlugin is distributing module dependencies. Ideally, each page on the website would serve a common file that includes the Webpack runtime and all shared dependencies, as well as a page-specific bundle.

Currently, all of the page-specific bundles use AMD-style definitions to list the modules they need to be available, which includes a reference to a ‘shared’ module.

So page-a.js would be something like:

require(['shared', 'a1', 'a2']);

And page-b.js:

require(['shared', 'b1', 'b2']);

And finally, shared.js:

require(['s1', 's2']);

The good news is that Webpack is correctly putting pretty much all of the shared bundle into its own chunk. However, the problem that I’m running into is that almost every module (a1, a2, b1, b2, s1, s2 …) has an AMD-declared dependency on jQuery, and Webpack is putting copies of jQuery into the page-specific chunks (both page-a and page-b), rather than the shared chunk. This means that as users visit multiple pages on the website, they have to re-download jQuery as part of each page-specific bundle’s chunk, rather than as a single download that can be cached as part of the shared chunk.

All page-specific bundles include the shared bundle as a dependency.

What can I do to get jQuery into the shared chunk and out of the page-specific chunks? I’ve been using documentation and examples like as a point of reference without success; at best, I’ve ended up with copies of jQuery in both the page-specific chunks and the shared chunk.

Author: Fantashit

2 thoughts on “Moving shared modules into common chunks

Comments are closed.