Last active
October 12, 2020 15:54
-
-
Save amygrinn/6cbd7fa3381eae9f5226043bf6261034 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
/** | |
* Tyler J Grinn | |
* [email protected] | |
* 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