-
Notifications
You must be signed in to change notification settings - Fork 8
/
module-html-plugin.js
48 lines (43 loc) · 1.69 KB
/
module-html-plugin.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
const HtmlWebpackPlugin = require("html-webpack-plugin")
const safariFix = `!function(){var e=document,t=e.createElement("script");if(!("noModule"in t)&&"onbeforeload"in t){var n=!1;e.addEventListener("beforeload",function(e){if(e.target===t)n=!0;else if(!e.target.hasAttribute("nomodule")||!n)return;e.preventDefault()},!0),t.type="module",t.src=".",e.head.appendChild(t),t.remove()}}();`
class ModuleHtmlPlugin {
constructor(isModule) {
this.isLegacyModule = isModule
this.isInjectsafariFixPolyfill = false
}
apply(compiler) {
const id = "ModuleHtmlPlugin"
compiler.hooks.compilation.tap(id, compilation => {
HtmlWebpackPlugin.getHooks(compilation).alterAssetTagGroups.tap(
id,
data => {
data.headTags.forEach(tag => {
// add script nomodule/module
if (tag.tagName === "script") {
if (/-legacy./.test(tag.attributes.src)) {
delete tag.attributes.type
tag.attributes.nomodule = ""
} else {
tag.attributes.type = "module"
}
}
})
if (this.isLegacyModule && !this.isInjectsafariFixPolyfill) {
this.isInjectsafariFixPolyfill = true
// inject Safari 10 nomdoule fix
data.headTags.unshift({
tagName: "script",
closeTag: true,
innerHTML: safariFix,
})
}
},
)
// 把<script nomudule=""> 处理成 <script nomudule>
HtmlWebpackPlugin.getHooks(compilation).beforeEmit.tap(id, data => {
data.html = data.html.replace(/\snomodule="">/g, " nomodule>")
})
})
}
}
module.exports = ModuleHtmlPlugin