Created
April 20, 2018 08:13
-
-
Save hiyangguo/41b9d5fb9a164b1043ff1e5fbb7cdceb to your computer and use it in GitHub Desktop.
HtmlWebpack插件处理 css 注入
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 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