-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathv4.ts
103 lines (88 loc) · 2.86 KB
/
v4.ts
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
103
import type { SyncHook } from 'tapable'
import type { Compiler } from 'webpack'
import HTMLWebpackPlugin = require('html-webpack-plugin')
import { TAP_KEY_PREFIX } from '../types'
import { BasePlugin } from './base-plugin'
interface BeforeAssetTagGenerationData {
outputName: string
assets: {
publicPath: string
css: string[]
}
plugin: HTMLWebpackPlugin
}
interface BeforeEmitData {
html: string
outputName: string
plugin: HTMLWebpackPlugin
}
interface HTMLWebpackPluginHooks {
beforeAssetTagGeneration: SyncHook<BeforeAssetTagGenerationData>
beforeEmit: SyncHook<BeforeEmitData>
}
type CSSStyle = string
export class PluginForHtmlWebpackPluginV4 extends BasePlugin {
// Using object reference to distinguish styles for multiple files
private cssStyleMap: Map<HTMLWebpackPlugin, CSSStyle[]> = new Map()
private prepareCSSStyle(data: BeforeAssetTagGenerationData) {
// `prepareCSSStyle` may be called more than once in webpack watch mode.
// https://github.com/Runjuu/html-inline-css-webpack-plugin/issues/30
// https://github.com/Runjuu/html-inline-css-webpack-plugin/issues/13
this.cssStyleMap.clear()
const [...cssAssets] = data.assets.css
cssAssets.forEach((cssLink) => {
if (this.isCurrentFileNeedsToBeInlined(cssLink)) {
const style = this.getCSSStyle({
cssLink,
publicPath: data.assets.publicPath,
})
if (style) {
if (this.cssStyleMap.has(data.plugin)) {
this.cssStyleMap.get(data.plugin)!.push(style)
} else {
this.cssStyleMap.set(data.plugin, [style])
}
const cssLinkIndex = data.assets.css.indexOf(cssLink)
// prevent generate <link /> tag
if (cssLinkIndex !== -1) {
data.assets.css.splice(cssLinkIndex, 1)
}
}
}
})
}
private process(data: BeforeEmitData) {
// check if current html needs to be inlined
if (this.isCurrentFileNeedsToBeInlined(data.outputName)) {
const cssStyles = this.cssStyleMap.get(data.plugin) || []
cssStyles.forEach((style) => {
data.html = this.addStyle({
style,
html: data.html,
htmlFileName: data.outputName,
})
})
data.html = this.cleanUp(data.html)
}
}
apply(compiler: Compiler) {
compiler.hooks.compilation.tap(
`${TAP_KEY_PREFIX}_compilation`,
(compilation) => {
const hooks: HTMLWebpackPluginHooks = (HTMLWebpackPlugin as any).getHooks(
compilation,
)
hooks.beforeAssetTagGeneration.tap(
`${TAP_KEY_PREFIX}_beforeAssetTagGeneration`,
(data) => {
this.prepare(compilation)
this.prepareCSSStyle(data)
},
)
hooks.beforeEmit.tap(`${TAP_KEY_PREFIX}_beforeEmit`, (data) => {
this.process(data)
})
},
)
}
}