Skip to content

Commit 2688cea

Browse files
committed
update:User plugin handle inject css
1 parent 1509f94 commit 2688cea

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
class HtmlWebpackHandleCssInjectPlugin {
2+
constructor(options = {}) {
3+
this.options = options;
4+
}
5+
6+
apply(compiler) {
7+
const handleHtmlWebpackPluginAfterHtmlProcessing = (data) => {
8+
const { filter } = this.options;
9+
if (!filter) {
10+
return;
11+
}
12+
data.html = data.html.replace(/<link .+?>(?=(?:<.+?>)*<\/head>)/g, (link) => {
13+
const filePath = link.match(/(href=")(.*)" /)[2];
14+
return filter(filePath, link) ? link : '';
15+
});
16+
return new Promise((resolve) => {
17+
resolve(data);
18+
});
19+
};
20+
21+
if (compiler.hooks) {
22+
// webpack 4 support
23+
compiler.hooks.compilation.tap('htmlWebpackPluginAfterHtmlProcessing', (compilation) => {
24+
compilation.hooks.htmlWebpackPluginAfterHtmlProcessing.tapPromise('htmlWebpackPluginAfterHtmlProcessing', handleHtmlWebpackPluginAfterHtmlProcessing);
25+
});
26+
} else {
27+
// Hook into the html-webpack-plugin processing
28+
compiler.plugin('compilation', (compilation) => {
29+
compilation.plugin('html-webpack-plugin-after-html-processing', handleHtmlWebpackPluginAfterHtmlProcessing);
30+
});
31+
}
32+
}
33+
}
34+
35+
module.exports = HtmlWebpackHandleCssInjectPlugin;

webpack.config.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ const fs = require('fs');
33
const webpack = require('webpack');
44
const ExtractTextPlugin = require('extract-text-webpack-plugin');
55
const HtmlwebpackPlugin = require('html-webpack-plugin');
6+
const HtmlWebpackHandleCssInjectPlugin = require('./HtmlWebpackHandleCssInjectPlugin');
67

78
const { STYLE_DEBUG } = process.env;
89
// 主题路径
@@ -88,6 +89,11 @@ module.exports = {
8889
title: 'webpack 多主题打包演示',
8990
template: 'src/index.html',
9091
inject: true
92+
}),
93+
new HtmlWebpackHandleCssInjectPlugin({
94+
filter: (filePath) => {
95+
return filePath.includes('style');
96+
}
9197
})
9298
],
9399
devtool: STYLE_DEBUG === 'SOURCE' && 'source-map'

0 commit comments

Comments
 (0)