Skip to content

Instantly share code, notes, and snippets.

@hiyangguo
Created April 20, 2018 08:13
Show Gist options
  • Save hiyangguo/41b9d5fb9a164b1043ff1e5fbb7cdceb to your computer and use it in GitHub Desktop.
Save hiyangguo/41b9d5fb9a164b1043ff1e5fbb7cdceb to your computer and use it in GitHub Desktop.
HtmlWebpack插件处理 css 注入
class HtmlWebpackHandleCssInjectPlugin {
constructor(options = {}) {
this.options = options;
}
apply(compiler) {
const handleHtmlWebpackPluginAfterHtmlProcessing = (data) => {
const { filter } = this.options;
if (!filter) {
return;
}
data.html = data.html.replace(/<link .+?>(?=(?:<.+?>)*<\/head>)/g, (link) => {
const filePath = link.match(/(href=")(.*)" /)[2];
return filter(filePath, link) ? link : '';
});
return new Promise((resolve) => {
resolve(data);
});
};
if (compiler.hooks) {
// webpack 4 support
compiler.hooks.compilation.tap('htmlWebpackPluginAfterHtmlProcessing', (compilation) => {
compilation.hooks.htmlWebpackPluginAfterHtmlProcessing.tapPromise('htmlWebpackPluginAfterHtmlProcessing', handleHtmlWebpackPluginAfterHtmlProcessing);
});
} else {
// Hook into the html-webpack-plugin processing
compiler.plugin('compilation', (compilation) => {
compilation.plugin('html-webpack-plugin-after-html-processing', handleHtmlWebpackPluginAfterHtmlProcessing);
});
}
}
}
module.exports = HtmlWebpackHandleCssInjectPlugin;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment