Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpack: extract common modules from entry and child chunks to separate commons chunk

I have an application built with webpack that uses code splitting. I now want to aggregate all common modules that match specific criteria (in this case node_modules) across all entry chunks and all child chunks (generated via code splitting) into a single separate commons chunk.

If I do this:

new webpack.optimize.CommonsChunkPlugin({
    children: true,
    async: 'vendor',
    minChunks: (module) => {
        const isVendor = module.context.split('/').some(dir => dir === 'vendor');
        return isVendor;
    },
}),

Webpack will aggregate all modules that match the minChunks function into a separate commons chunk, but only for modules from child chunks—it will not aggregate modules from the entry chunk into the commons chunk. As a result, I have duplicated modules that appear in both my entry chunk and commons chunk.

How is this possible?


Example: https://github.com/OliverJAsh/webpack-commons-vendor/blob/f524bfdb0e047161c453a6b84f89ab6d25d6c648/webpack.config.js

enter image description here

like image 770
Oliver Joseph Ash Avatar asked Dec 07 '17 13:12

Oliver Joseph Ash


1 Answers

You need to create a webpack DLL that contains all your commonly used libs.

https://webpack.js.org/plugins/dll-plugin/

An example on how to set this up can be found in React-Boilerplate.

https://github.com/react-boilerplate/react-boilerplate/blob/master/internals/webpack/webpack.dll.babel.js

And here is the config for the example.

https://github.com/react-boilerplate/react-boilerplate/blob/master/internals/config.js

like image 130
David Bradshaw Avatar answered Sep 28 '22 23:09

David Bradshaw