Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
/**
* Tyler J Grinn
* tylergrinn@gmail.com
* License: MIT
*/
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = class HtmlWebpackExcludeAssetsPlugin {
static PLUGIN_NAME = 'Html webpack exclude assets plugin';
/**
*
* @param {...{ entry: string, ext: string }} patterns ***Patterns:** Any number of descriptions
* of assets to remove. Each pattern needs an
*
* `entry` and `ext`
*
* property. If an asset matches both, it will be removed from the compilation and from
* any html file generated by html-webpack-plugin.
*
* **Note:** if your entry is not named you should use 'main' for the entry.
*/
constructor(...patterns) {
this.patterns = patterns || [];
}
apply(compiler) {
compiler.hooks.compilation.tap(
HtmlWebpackExcludeAssetsPlugin.PLUGIN_NAME,
(compilation) => {
HtmlWebpackPlugin.getHooks(compilation).beforeAssetTagGeneration.tap(
HtmlWebpackExcludeAssetsPlugin.PLUGIN_NAME,
(htmlWebpackData) => {
this.patterns.forEach((pattern) => {
if (compilation.entrypoints.has(pattern.entry)) {
const entrypoint = compilation.entrypoints.get(pattern.entry);
const files = entrypoint.getEntrypointChunk().files;
files.forEach((file) => {
if (file.split('.').slice(-1)[0] === pattern.ext) {
compilation.deleteAsset(file);
if (pattern.ext in htmlWebpackData.assets) {
htmlWebpackData.assets[
pattern.ext
] = htmlWebpackData.assets[pattern.ext].filter(
(f) => f !== file
);
}
}
});
}
});
return htmlWebpackData;
}
);
}
);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment