TheCommonsChunkPlugin
is an opt-in feature that creates a separate file (known as a chunk), consisting of common modules shared between multiple entry points.
The CommonsChunkPlugin has been removed in webpack v4 legato. To learn how chunks are treated in the latest version, check out theSplitChunksPlugin.
By separating common modules from bundles, the resulting chunked file can be loaded once initially, and stored in cache for later use. This results in page speed optimizations as the browser can quickly serve the shared code from cache, rather than being forced to load a larger bundle whenever a new page is visited.
newwebpack.optimize.CommonsChunkPlugin(options);
{ name:string,// or names:string[],// The chunk name of the commons chunk. An existing chunk can be selected by passing a name of an existing chunk.// If an array of strings is passed this is equal to invoking the plugin multiple times for each chunk name.// If omitted and `options.async` or `options.children` is set all chunks are used, otherwise `options.filename`// is used as chunk name.// When using `options.async` to create common chunks from other async chunks you must specify an entry-point// chunk name here instead of omitting the `option.name`. filename:string,// The filename template for the commons chunk. Can contain the same placeholders as `output.filename`.// If omitted the original filename is not modified (usually `output.filename` or `output.chunkFilename`).// This option is not permitted if you're using `options.async` as well, see below for more details. minChunks:number|Infinity|function(module, count)=>boolean,// The minimum number of chunks which need to contain a module before it's moved into the commons chunk.// The number must be greater than or equal 2 and lower than or equal to the number of chunks.// Passing `Infinity` creates the commons chunk, but moves no modules into it.// By providing a `function` you can add custom logic. (Defaults to the number of chunks) chunks:string[],// Select the source chunks by chunk names. The chunk must be a child of the commons chunk.// If omitted all entry chunks are selected. children:boolean,// If `true` all children of the commons chunk are selected deepChildren:boolean,// If `true` all descendants of the commons chunk are selectedasync:boolean|string,// If `true` a new async commons chunk is created as child of `options.name` and sibling of `options.chunks`.// It is loaded in parallel with `options.chunks`.// Instead of using `option.filename`, it is possible to change the name of the output file by providing// the desired string here instead of `true`. minSize:number,// Minimum size of all common module before a commons chunk is created.}
Generate an extra chunk, which contains common modules shared between entry points.
newwebpack.optimize.CommonsChunkPlugin({ name:'commons',// (the commons chunk name) filename:'commons.js',// (the filename of the commons chunk)// minChunks: 3,// (Modules must be shared between 3 entries)// chunks: ["pageA", "pageB"],// (Only use these entries)});
You must load the generated chunk before the entry point:
<scriptsrc="commons.js"charset="utf-8"></script><scriptsrc="entry.bundle.js"charset="utf-8"></script>
Split your code into vendor and application.
module.exports={//... entry:{ vendor:['jquery','other-lib'], app:'./entry',}, plugins:[newwebpack.optimize.CommonsChunkPlugin({ name:'vendor',// filename: "vendor.js"// (Give the chunk a different name) minChunks:Infinity,// (with more entries, this ensures that no other module// goes into the vendor chunk)}),],};
<scriptsrc="vendor.js"charset="utf-8"></script><scriptsrc="app.js"charset="utf-8"></script>
In combination with long term caching you may need to use theChunkManifestWebpackPlugin
to avoid the vendor chunk changes. You should also use records to ensure stable module ids, e.g. usingNamedModulesPlugin
orHashedModuleIdsPlugin
.
WithCode Splitting, multiple child chunks of an entry chunk can have common dependencies. To prevent duplication these can be moved into the parent. This reduces overall size, but does have a negative effect on the initial load time. If it is expected that users will need to download many sibling chunks, i.e. children of the entry chunk, then this should improve load time overall.
newwebpack.optimize.CommonsChunkPlugin({// names: ["app", "subPageA"]// (choose the chunks, or omit for all chunks) children:true,// (select all children of chosen chunks)// minChunks: 3,// (3 children must share the module before it's moved)});
Similar to the above one, but instead of moving common modules into the parent (which increases initial load time) a new async-loaded additional commons chunk is used. This is automatically downloaded in parallel when the additional chunk is downloaded.
newwebpack.optimize.CommonsChunkPlugin({ name:'app',// or names:['app','subPageA'],// the name or list of names must match the name or names// of the entry points that create the async chunks children:true,// (use all children of the chunk) async:true,// (create an async commons chunk) minChunks:3,// (3 children must share the module before it's separated)});
minChunks
property a functionYou also have the ability to pass theminChunks
property a function. This function is called by theCommonsChunkPlugin
and calls the function withmodule
andcount
arguments.
Themodule
argument represents each module in the chunks you have provided via thename
/names
property.module
has the shape of aNormalModule, which has two particularly useful properties for this use case:
module.context
: The directory that stores the file. For example:'/my_project/node_modules/example-dependency'
module.resource
: The name of the file being processed. For example:'/my_project/node_modules/example-dependency/index.js'
Thecount
argument represents how many chunks themodule
is used in.
This option is useful when you want to have fine-grained control over how the CommonsChunk algorithm determines where modules should be moved to.
newwebpack.optimize.CommonsChunkPlugin({ name:'my-single-lib-chunk', filename:'my-single-lib-chunk.js',minChunks:function(module, count){// If module has a path, and inside of the path exists the name "somelib",// and it is used in 3 separate chunks/entries, then break it out into// a separate chunk with chunk keyname "my-single-lib-chunk", and filename "my-single-lib-chunk.js"return module.resource&&/somelib/.test(module.resource)&& count===3;},});
As seen above, this example allows you to move only one lib to a separate file if and only if all conditions are met inside the function.
This concept may be used to obtain implicit common vendor chunks:
newwebpack.optimize.CommonsChunkPlugin({ name:'vendor',minChunks:function(module){// this assumes your vendor imports exist in the node_modules directoryreturn module.context&& module.context.includes('node_modules');},});
To extract the webpack bootstrap logic into a separate file, use theCommonsChunkPlugin
on aname
which is not defined asentry
. Commonly the namemanifest
is used. See thecaching guide for details.
newwebpack.optimize.CommonsChunkPlugin({ name:'manifest', minChunks:Infinity,});
Since thevendor
andmanifest
chunk use a different definition forminChunks
, you need to invoke the plugin twice:
[newwebpack.optimize.CommonsChunkPlugin({ name:'vendor',minChunks:function(module){return module.context&& module.context.includes('node_modules');},}),newwebpack.optimize.CommonsChunkPlugin({ name:'manifest', minChunks:Infinity,}),];