Skip to content

Instantly share code, notes, and snippets.

@Jessidhia
Created November 4, 2016 02:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jessidhia/864e46adfa950e11930492fee4581038 to your computer and use it in GitHub Desktop.
Save Jessidhia/864e46adfa950e11930492fee4581038 to your computer and use it in GitHub Desktop.
CommonsChunkPlugin setting to make a sync common chunk of async child chunks
// having `entry: { main: path.resolve('src') }`:
new webpack.optimize.CommonsChunkPlugin({
name: 'common',
chunks: ['main'],
// "children" does not actually select all the children of "chunks",
// but completely ignores all "chunks" and selects the children of "name"
// instead, so it's useless for our use case, as we're making a new chunk.
minChunks: (() => {
const tag = `${__filename}-common-minChunks`
// the count argument will always be "1" as there's only one chunk in
// "chunks", so we need to count the sub-chunks ourselves.
const chunks = new Set()
return module => {
// look at each of the reason modules (i.e. this module's parents) and
// tally the unique chunks where the modules appear
module.reasons.forEach(reason => {
reason.module.chunks.forEach(chunk => chunks.add(chunk))
})
// we only care about the count of unique chunks (the size)
const size = chunks.size
chunks.clear()
// if they're in more than one unique chunk (including entry chunk), then it's shared
if (size >= 2) {
module[tag] = true
return true
} else if (module.reasons.length > 0) {
// also move it in if all parents have been moved in
if (module.reasons.every(reason => reason.module[tag])) {
module[tag] = true
return true
}
}
return false
}
})()
}),
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment