Skip to content

Instantly share code, notes, and snippets.

@gribnoysup
Created February 9, 2017 10:21
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 gribnoysup/68c0a9713901eced85d4d95857d6e787 to your computer and use it in GitHub Desktop.
Save gribnoysup/68c0a9713901eced85d4d95857d6e787 to your computer and use it in GitHub Desktop.
Add additional (child) chunks to HtmlWebpackPlugin
class HtmlAdditionalChunksPlugin {
constructor(chunks = []) {
this.chunks = chunks
this.onBeforeGeneration = 'html-webpack-plugin-before-html-generation'
}
findChunk(chunk, chunkName) {
return Array.isArray(chunk.names) && chunk.names[0] === chunkName
}
getChunks(compilation) {
const appChunks = compilation.getStats().toJson().chunks
return this.chunks.reduce((chunks, chunkName) => {
const chunk = appChunks.find((chunk) => this.findChunk(chunk, chunkName))
if (chunk) chunks.push(chunk)
return chunks
}, [])
}
apply(compiler) {
compiler.plugin('compilation', (compilation) => {
compilation.plugin(this.onBeforeGeneration, (data, callback) => {
const chunks = this.getChunks(compilation)
const publicPath = data.assets.publicPath ? data.assets.publicPath : ''
chunks.forEach((chunk) => {
const jsPath = chunk.files.find((fileName) => /\.js$/.test(fileName))
const cssPath = chunk.files.find((fileName) => /\.css$/.test(fileName))
if (!jsPath) return
data.assets.chunks[chunk.names[0]] = {
size: chunk.size,
entry: publicPath + jsPath,
css: cssPath ? [publicPath + cssPath] : [],
hash: chunk.hash
}
data.assets.js.push(publicPath + jsPath)
if (cssPath) data.assets.css.push(publicPath + cssPath)
})
callback(null, data)
})
})
}
}
module.exports = HtmlAdditionalChunksPlugin
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment