-
Notifications
You must be signed in to change notification settings - Fork 15
/
index.js
53 lines (46 loc) · 1.87 KB
/
index.js
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
53
const webpack = require('webpack')
const _ = require('lodash')
const chalk = require('chalk')
const assert = require('assert')
const beautify = require('js-beautify').html
const webpackLatest = !_.isNil(webpack.version) && /.*4(\.\d+){0,2}/gi.test(webpack.version)
function HtmlBeautifyPlugin ({ config = {}, replace } = { config: {}, replace: [] }) {
assert(config && typeof config === 'object' , chalk.red('Beautify config should be an object.'))
this.options = {
config: _.merge({
indent_size: 4,
indent_with_tabs: false,
html: {
end_with_newline: true,
indent_inner_html: true,
preserve_newlines: true,
}
}, config),
replace: replace || []
}
}
function htmlPluginDataFunction (htmlPluginData, callback, _this) {
htmlPluginData.html = beautify(_.reduce(_this.options.replace, (res, item) => {
if(typeof item === 'string' || item instanceof RegExp)
return res.replace(item instanceof RegExp ? item : new RegExp(item, 'gi'), '')
else
return res.replace(item.test instanceof RegExp ? item.test : new RegExp(item.test, 'gi'), item.with || '')
}, htmlPluginData.html), _this.options.config)
callback(null, htmlPluginData)
}
HtmlBeautifyPlugin.prototype.apply = function (compiler) {
if (!webpackLatest) {
compiler.plugin('compilation', compilation =>
compilation.plugin('html-webpack-plugin-after-html-processing', (htmlPluginData, callback) => {
htmlPluginDataFunction(htmlPluginData, callback, this)
})
)
} else {
compiler.hooks.compilation.tap('HtmlBeautifyPlugin', compilation =>
compilation.hooks.htmlWebpackPluginAfterHtmlProcessing.tapAsync('HtmlBeautifyPlugin', (htmlPluginData, callback) => {
htmlPluginDataFunction(htmlPluginData, callback, this)
})
)
}
}
module.exports = HtmlBeautifyPlugin