-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
59 lines (48 loc) · 1.98 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
const HtmlWebpackPlugin = require('html-webpack-plugin')
const PluginName = 'InlineAssetsHtmlPlugin'
const InlineTypes = [
{ assetTagName: 'script', srcAttr: 'src', inlineTagName: 'script' },
{ assetTagName: 'link', srcAttr: 'href', inlineTagName: 'style' }
]
class InlineAssetsHtmlPlugin {
constructor(options = {}) {
if (!options.test) throw Error(`${PluginName}: option 'test' is required.`)
this.options = options
}
resolveTag(publicPath, assets, tag) {
const inlineType = InlineTypes.find((type) => type.assetTagName === tag.tagName && !!tag.attributes[type.srcAttr])
if (!inlineType) return tag
const src = tag.attributes[inlineType.srcAttr]
const assetName = publicPath ? src.replace(publicPath, '') : src
const asset = assets[assetName]
if (!asset) return tag
if (!this.options.test.test(assetName)) return tag
return { tagName: inlineType.inlineTagName, innerHTML: asset.source(), closeTag: true }
}
apply(compiler) {
let publicPath = compiler.options.output.publicPath || ''
if (publicPath && !publicPath.endsWith('/')) publicPath += '/'
compiler.hooks.compilation.tap(PluginName, (compilation) => {
const tagFunction = (tag) => this.resolveTag(publicPath, compilation.assets, tag)
const hooks = HtmlWebpackPlugin.getHooks(compilation)
hooks.alterAssetTagGroups.tap(PluginName, (assets) => {
assets.headTags = assets.headTags.map(tagFunction)
assets.bodyTags = assets.bodyTags.map(tagFunction)
})
if (this.options.emit) return
compilation.hooks.processAssets.tapAsync(
{
name: PluginName,
stage: compiler.webpack.Compilation.PROCESS_ASSETS_STAGE_OPTIMIZE_INLINE
},
(compilationAssets, callback) => {
Object.keys(compilationAssets).forEach((name) => {
if (this.options.test.test(name)) delete compilationAssets[name]
})
callback()
}
)
})
}
}
module.exports = InlineAssetsHtmlPlugin