-
Notifications
You must be signed in to change notification settings - Fork 19
/
index.js
84 lines (69 loc) · 3.04 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
var sourceMappingURL = require('source-map-url')
function InlineManifestWebpackPlugin (name) {
this.name = name || 'runtime'
}
InlineManifestWebpackPlugin.prototype.apply = function (compiler) {
var name = this.name
compiler.hooks.emit
.tap('InlineManifestWebpackPlugin', function (compilation) {
delete compilation.assets[getAssetName(compilation.chunks, name)]
})
compiler.hooks.compilation
.tap('InlineManifestWebpackPlugin', function (compilation) {
compilation.hooks.htmlWebpackPluginAlterAssetTags
.tapAsync('InlineManifestWebpackPlugin', function (data, cb) {
var manifestAssetName = getAssetName(compilation.chunks, name)
if (manifestAssetName) {
['head', 'body'].forEach(function (section) {
data[section] = inlineWhenMatched(
compilation,
data[section],
manifestAssetName
)
})
}
cb(null, data)
})
compilation.hooks.htmlWebpackPluginBeforeHtmlGeneration
.tapAsync('InlineManifestWebpackPlugin', function (htmlPluginData, cb) {
var runtime = []
var assets = htmlPluginData.assets
var manifestAssetName = getAssetName(compilation.chunks, name)
if (manifestAssetName && htmlPluginData.plugin.options.inject === false) {
runtime.push('<script>')
runtime.push(sourceMappingURL.removeFrom(compilation.assets[manifestAssetName].source()))
runtime.push('</script>')
var runtimeIndex = assets.js.indexOf(assets.publicPath + manifestAssetName)
if (runtimeIndex >= 0) {
assets.js.splice(runtimeIndex, 1)
delete assets.chunks[name]
}
}
assets.runtime = runtime.join('')
cb(null, htmlPluginData)
})
})
}
function getAssetName (chunks, chunkName) {
return (chunks.filter(function (chunk) {
return chunk.name === chunkName
})[0] || {files: []}).files[0]
}
function inlineWhenMatched (compilation, scripts, manifestAssetName) {
return scripts.map(function (script) {
var isManifestScript = script.tagName === 'script' &&
(script.attributes.src.indexOf(manifestAssetName) >= 0)
if (isManifestScript) {
return {
tagName: 'script',
closeTag: true,
attributes: {
type: 'text/javascript'
},
innerHTML: sourceMappingURL.removeFrom(compilation.assets[manifestAssetName].source())
}
}
return script
})
}
module.exports = InlineManifestWebpackPlugin