This repository has been archived by the owner on Apr 9, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
102 lines (97 loc) · 2.9 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
93
94
95
96
97
98
99
100
101
102
"use strict";
let js = [];
let run = 0;
let outputFileNameRegex = [];
function HtmlWebpackMultiBuildPlugin(options) {
this.options = options;
}
HtmlWebpackMultiBuildPlugin.prototype = {
apply: function(compiler) {
this.createOutputRegexes(compiler.options);
if (compiler.hooks) {
// webpack 4 support
compiler.hooks.compilation.tap(
"HtmlWebpackMultiBuildPlugin",
compilation => {
if (compilation.hooks.htmlWebpackPluginBeforeHtmlGeneration) {
compilation.hooks.htmlWebpackPluginBeforeHtmlGeneration.tapAsync(
"HtmlWebpackMultiBuildPlugin",
this.beforeHtmlGeneration.bind(this)
);
} else {
var HtmlWebpackPlugin = require("html-webpack-plugin");
var hooks = HtmlWebpackPlugin.getHooks(compilation);
hooks.beforeAssetTagGeneration.tapAsync(
"HtmlWebpackMultiBuildPlugin",
this.beforeHtmlGeneration.bind(this)
);
}
}
);
} else {
compiler.plugin("compilation", compilation => {
compilation.plugin(
"html-webpack-plugin-before-html-generation",
this.beforeHtmlGeneration.bind(this)
);
});
}
},
beforeHtmlGeneration: function(data, cb) {
this.clearOldScripts(data);
++run;
js = js.concat(data.assets.js);
data.assets.js = js;
if (run === 2) {
data.plugin.options.modernScripts = js.filter(
value => value.indexOf("legacy") === -1
);
data.plugin.options.legacyScripts = js.filter(
value => value.indexOf("legacy") > 0
);
}
cb(null, data);
},
createOutputRegexes: function(options) {
if (options.output && options.output.filename) {
// default webpack entry
let entry = ["main"];
if (options.entry) {
// when object is provided we have custom entry names
if (typeof options.entry === "object") {
entry = Object.keys(options.entry);
}
}
entry.forEach(e => {
const outFilePathForEntry = options.output.filename.replace(
"[name]",
e
);
const matches = outFilePathForEntry.match(/\[hash(:\d+)?]/);
if (matches) {
// max hash length is 20 characters so limit the regex to 20
const hashLength = matches[1] ? +matches[1].substr(1) : 20;
outputFileNameRegex.push(
new RegExp(
outFilePathForEntry.replace(
matches[0],
`[\\w\\d]{${Math.min(hashLength, 20)}}`
)
)
);
}
});
}
},
clearOldScripts: function(data) {
outputFileNameRegex.forEach(r => {
data.assets.js.forEach(a => {
// we have one of our entries
if (r.test(a)) {
js = js.filter(j => !r.test(j));
}
});
});
}
};
module.exports = HtmlWebpackMultiBuildPlugin;