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

1

9

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

Danielson answered 7/12, 2017 at 13:15 Comment(0)
S
5

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

Susiesuslik answered 13/12, 2017 at 23:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.