This repository has been archived by the owner on Jun 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
92 lines (85 loc) · 2.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
const path = require("path");
const fs = require("fs");
const HtmlWebpackPlugin = require('html-webpack-plugin');
class HtmlWebpackExcludeEmptyAssetsPlugin {
constructor(options = {}) {
this.minBytes = options.minBytes || 1024; // 1 KB minimum size
this.PLUGIN = "HtmlWebpackExcludeEmptyAssetsPlugin";
}
apply(compiler) {
compiler.hooks.compilation.tap(this.PLUGIN, (compilation) => {
if(compilation.hooks) {
// webpack 4.x and later
if(compilation.hooks['htmlWebpackPluginAlterAssetTags']) {
compilation.hooks['htmlWebpackPluginAlterAssetTags'].tap(this.PLUGIN, (htmlPluginData) => {
const result = this.processAssets(htmlPluginData, compilation);
return Promise.resolve(result);
});
} else {
// HtmlWebpackPlugin 4.x and later
const hooks = HtmlWebpackPlugin.getHooks(compilation);
hooks["alterAssetTags"].tap(this.PLUGIN, (htmlPluginData) => {
const result = this.processAssets(htmlPluginData, compilation);
return Promise.resolve(result);
});
}
} else {
// webpack 3.x and earlier
compilation.plugin(
"html-webpack-plugin-alter-asset-tags",
(htmlPluginData, callback) => {
const result = this.processAssets(htmlPluginData, compilation);
if (callback) {
callback(null, result);
} else {
return Promise.resolve(result);
}
}
);
}
});
}
processAssets(pluginData, compilation) {
const base = JSON.parse(pluginData.plugin.assetJson)[0];
const filterTag = (tag) =>
!["link", "script"].includes(tag.tagName) ||
!Boolean(tag.attributes) ||
!this.isEmpty(
tag.attributes.src || tag.attributes.href,
base,
compilation
);
if(compilation.hooks) {
// webpack 4.x and later
var scripts = pluginData.assetTags.scripts.filter(filterTag);
var styles = pluginData.assetTags.styles.filter(filterTag);
return Promise.resolve({
assetTags: {
scripts: scripts,
styles: styles,
meta: pluginData.assetTags.meta,
},
outputName: pluginData.outputName,
plugin: pluginData.plugin,
});
} else {
// webpack 3.x and earlier
return {
head: pluginData.head.filter(filterTag),
body: pluginData.body.filter(filterTag),
plugin: pluginData.plugin,
chunks: pluginData.chunks,
outputName: pluginData.outputName,
};
}
}
isEmpty(assetPath, base, compilation) {
const rel = assetPath.substr(base.length);
const source = compilation.assets[rel];
if (source && source.size) {
return source.size() === 0 || source.size() <= this.minBytes;
}
return false;
}
}
module.exports = HtmlWebpackExcludeEmptyAssetsPlugin;