index.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. function ReplaceHtmlStyles() {
  2. this.replace = function(htmlPluginData, callback) {
  3. //console.log(htmlPluginData);
  4. let html = htmlPluginData.html;
  5. // //console.log(html);
  6. let htmlRegx = new RegExp("\\<style[^\\>]*\\>.*?\\<\\/style\\>", "g");
  7. let match = html.match(htmlRegx);
  8. if (match) {
  9. //console.log(match)
  10. html = html.replace(htmlRegx, "");
  11. //console.log(html)
  12. match.forEach((item, index) => {
  13. html = html.replace(/<\/body>/, item + "</body>");
  14. });
  15. htmlPluginData.html = html;
  16. }
  17. callback(null, htmlPluginData);
  18. };
  19. }
  20. ReplaceHtmlStyles.prototype.apply = function(compiler) {
  21. if (compiler.hooks) {
  22. compiler.hooks.compilation.tap("ReplaceHtmlStyles", compilation => {
  23. if (compilation.hooks.htmlWebpackPluginAfterHtmlProcessing) {
  24. compilation.hooks.htmlWebpackPluginAfterHtmlProcessing.tapAsync(
  25. "ReplaceHtmlStyles",
  26. this.replace
  27. );
  28. } else {
  29. var HtmlWebpackPlugin = require("html-webpack-plugin");
  30. if (!HtmlWebpackPlugin) {
  31. throw new Error(
  32. "Please ensure that `html-webpack-plugin` was placed before `replace-html-styles` in your Webpack config if you were working with Webpack 4.x!"
  33. );
  34. }
  35. HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tapAsync(
  36. "ReplaceHtmlStyles",
  37. this.replace
  38. );
  39. }
  40. });
  41. } else {
  42. compiler.plugin("compilation", compilation => {
  43. compilation.plugin("html-webpack-plugin-beforeEmit", this.replace);
  44. });
  45. }
  46. };
  47. module.exports = ReplaceHtmlStyles;