-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
40 lines (38 loc) · 1.63 KB
/
index.js
File metadata and controls
40 lines (38 loc) · 1.63 KB
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
class HtmlScriptInjection {
constructor(options) {
this.options = options || {};
}
apply(compiler){
let isInject = !!this.options.injectPoint;
compiler.hooks.compilation.tap('HtmlScriptInjection', (compilation)=> {
let inlineScripts = '';
let scriptRule = /(<script\b[^>]*>([\s\S]*?)<\/script>)/g;
let injectRule = /(<!--[\s]*script[\s]*-->)[\w,\W]*(<!--[\s]*script[\s]end[\s]*-->)/g;
compilation.hooks.htmlWebpackPluginBeforeHtmlProcessing.tapAsync(
'HtmlScriptInjection',
(data, cb) => {
inlineScripts = data.html.match(scriptRule) ? data.html.match(scriptRule).join(''): '';
data.html = data.html.replace(scriptRule,'');
cb();
}
);
compilation.hooks.htmlWebpackPluginAfterHtmlProcessing.tapAsync(
'HtmlScriptInjection',
(data, cb) => {
inlineScripts += '</body>';
let html = data.html.replace(/<[\s]*\/body[\s]*>/,inlineScripts);
let isExistInjectPoint = injectRule.test(data.html);
if(isInject && isExistInjectPoint){
let allScripts = html.match(scriptRule).join('');
html = html.replace(scriptRule,'');
data.html = html.replace(injectRule, allScripts);
} else {
data.html = html;
}
cb();
}
);
});
}
}
module.exports = HtmlScriptInjection;