Created
February 9, 2017 10:21
-
-
Save gribnoysup/68c0a9713901eced85d4d95857d6e787 to your computer and use it in GitHub Desktop.
Add additional (child) chunks to HtmlWebpackPlugin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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