扩展html-webpack-plugin

打包对文件的修改

在打包生成文件到dist前修改文本

我们修改一个打包index.html文件里css里的url(./#/#.png)
给打包的后的图片引入添加时间戳

  1. 创建一个函数
1
2
3
4
5
6
function MyPlugin(options) {
/*
param{*} options 这是想要传入的参数(可以传值,也可以在需要添加的位置生成时间戳)
*/
this.options = options;
}
1
2
var webpack = require("webpack")
var HtmlWebpackPlugin = require("html-webpack-plugin")
  1. 我创建时间戳,插入到webpack导出的script之前。
1
2
3
4
5
6
7
8
/*
这里可以传参
*/
new MyPlugin({
"timer":"123456"
}),

这里是要写在plugins数组里面
  • webpack 会给我们提供的回调函数提供参数,我们可以注册编译阶段的事件了。html-webpack-plugin 提供了一系列事件。

  • Async:

    • html-webpack-plugin-before-html-generation

    • html-webpack-plugin-before-html-processing

    • html-webpack-plugin-alter-asset-tags
    • html-webpack-plugin-after-html-processing
    • html-webpack-plugin-after-emit
  • Sync:
    • html-webpack-plugin-alter-chunks
  1. 我们可以注册到它处理HTML之前,使用html-webpack-plugin-before-html-processing 事件。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32

const jsdom = require("jsdom");
//操作DOM要在这引入找个包
const { JSDOM } = jsdom;


MyPlugin.prototype.apply = function (compiler) {
var timer = this.options.timer;
compiler.plugin('compilation', (compilation, options) => {
compilation.plugin(
'html-webpack-plugin-before-html-processing',
(data, cb) => {
//这里的data是打包要生成的文件,可进行修改操作

//用正则匹配了一下带.png的地方给加戳
data = JSON.stringify(data)
var result = data.replace(/.png/g, '.png?v='+timer);
data = JSON.parse(result)


//操作DOM要进行转换
var dom = new JSDOM(data.html);

....这里操作DOM

data.html = dom.serialize();//把修改的DOM树附上去,然后返回出去
cb(null, data)
}
)

})
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
const jsdom = require("jsdom");
//操作DOM要在这引入找个包
const { JSDOM } = jsdom;
var timer = Date.now();

function MyPlugin(options) {
this.options = options;
}

MyPlugin.prototype.apply = function (compiler) {
var timer = this.options.timer;
compiler.plugin('compilation', (compilation, options) => {
compilation.plugin(
'html-webpack-plugin-before-html-processing',
(data, cb) => {
//这里的data是打包要生成的文件,可进行修改操作

//用正则匹配了一下带.png的地方给加戳
data = JSON.stringify(data)
var result = data.replace(/.png/g, '.png?v='+timer);
data = JSON.parse(result)


//操作DOM要进行转换
var dom = new JSDOM(data.html);

....这里操作DOM

data.html = dom.serialize();//把修改的DOM树附上去,然后返回出去
cb(null, data)
}
)

})
}

plugins:[
new HtmlWebpackPlugin({
filename: path.resolve(__dirname, config.build.index),
template: "src/index.html",
chunksSortMode: "dependency",
inject: true,
minify: {
collapseWhitespace: true,
removeAttributeQuotes: true,
removeComments: true
}
}),
new MyPlugin({
"timer":"123456"
}),
]
分享到