Skip to content

Commit

Permalink
update:User plugin handle inject css
Browse files Browse the repository at this point in the history
  • Loading branch information
hiyangguo committed Apr 20, 2018
1 parent 1509f94 commit 2688cea
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
35 changes: 35 additions & 0 deletions HtmlWebpackHandleCssInjectPlugin.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
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;
6 changes: 6 additions & 0 deletions webpack.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ const fs = require('fs');
const webpack = require('webpack');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlwebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackHandleCssInjectPlugin = require('./HtmlWebpackHandleCssInjectPlugin');

const { STYLE_DEBUG } = process.env;
// 主题路径
Expand Down Expand Up @@ -88,6 +89,11 @@ module.exports = {
title: 'webpack 多主题打包演示',
template: 'src/index.html',
inject: true
}),
new HtmlWebpackHandleCssInjectPlugin({
filter: (filePath) => {
return filePath.includes('style');
}
})
],
devtool: STYLE_DEBUG === 'SOURCE' && 'source-map'
Expand Down

0 comments on commit 2688cea

Please sign in to comment.