-
Notifications
You must be signed in to change notification settings - Fork 28k
/
Copy pathReactRefreshWebpackPlugin.ts
183 lines (169 loc) · 6.16 KB
/
ReactRefreshWebpackPlugin.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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
import type {
Compiler as WebpackCompiler,
Template as WebpackTemplate,
RuntimeModule as WebpackRuntimeModule,
RuntimeGlobals as WebpackRuntimeGlobals,
Compilation as WebpackCompilation,
} from 'webpack'
// Shared between webpack 4 and 5:
function injectRefreshFunctions(
compilation: WebpackCompilation,
Template: typeof WebpackTemplate
) {
const hookVars: any = (compilation.mainTemplate.hooks as any).localVars
hookVars.tap('ReactFreshWebpackPlugin', (source: string) =>
Template.asString([
source,
'',
'// noop fns to prevent runtime errors during initialization',
'if (typeof self !== "undefined") {',
Template.indent('self.$RefreshReg$ = function () {};'),
Template.indent('self.$RefreshSig$ = function () {'),
Template.indent(Template.indent('return function (type) {')),
Template.indent(Template.indent(Template.indent('return type;'))),
Template.indent(Template.indent('};')),
Template.indent('};'),
'}',
])
)
}
function webpack4(this: ReactFreshWebpackPlugin, compiler: WebpackCompiler) {
const { Template } = this
// Webpack 4 does not have a method to handle interception of module
// execution.
// The closest thing we have to emulating this is mimicking the behavior of
// `strictModuleExceptionHandling` in `MainTemplate`:
// https://github.com/webpack/webpack/blob/4c644bf1f7cb067c748a52614500e0e2182b2700/lib/MainTemplate.js#L200
compiler.hooks.compilation.tap('ReactFreshWebpackPlugin', (compilation) => {
injectRefreshFunctions(compilation, Template)
const hookRequire: any = (compilation.mainTemplate.hooks as any).require
// @ts-ignore webpack 5 types compat
hookRequire.tap('ReactFreshWebpackPlugin', (source: string) => {
// Webpack 4 evaluates module code on the following line:
// ```
// modules[moduleId].call(module.exports, module, module.exports, hotCreateRequire(moduleId));
// ```
// https://github.com/webpack/webpack/blob/4c644bf1f7cb067c748a52614500e0e2182b2700/lib/MainTemplate.js#L200
const lines = source.split('\n')
// @ts-ignore webpack 5 types compat
const evalIndex = lines.findIndex((l) =>
l.includes('modules[moduleId].call(')
)
// Unable to find the module execution, that's OK:
if (evalIndex === -1) {
return source
}
// Legacy CSS implementations will `eval` browser code in a Node.js
// context to extract CSS. For backwards compatibility, we need to check
// we're in a browser context before continuing.
return Template.asString([
...lines.slice(0, evalIndex),
`
var hasRefresh = typeof self !== "undefined" && !!self.$RefreshInterceptModuleExecution$;
var cleanup = hasRefresh
? self.$RefreshInterceptModuleExecution$(moduleId)
: function() {};
try {
`,
lines[evalIndex],
`
} finally {
cleanup();
}
`,
...lines.slice(evalIndex + 1),
])
})
})
}
function webpack5(this: ReactFreshWebpackPlugin, compiler: WebpackCompiler) {
const { RuntimeGlobals, RuntimeModule, Template } = this
class ReactRefreshRuntimeModule extends RuntimeModule {
constructor() {
super('react refresh', 5)
}
generate() {
const { runtimeTemplate } = this.compilation!
return Template.asString([
`if (${RuntimeGlobals.interceptModuleExecution}) {`,
`${
RuntimeGlobals.interceptModuleExecution
}.push(${runtimeTemplate.basicFunction('options', [
`${
runtimeTemplate.supportsConst() ? 'const' : 'var'
} originalFactory = options.factory;`,
`options.factory = ${runtimeTemplate.basicFunction(
'moduleObject, moduleExports, webpackRequire',
[
// Legacy CSS implementations will `eval` browser code in a Node.js
// context to extract CSS. For backwards compatibility, we need to check
// we're in a browser context before continuing.
`${
runtimeTemplate.supportsConst() ? 'const' : 'var'
} hasRefresh = typeof self !== "undefined" && !!self.$RefreshInterceptModuleExecution$;`,
`${
runtimeTemplate.supportsConst() ? 'const' : 'var'
} cleanup = hasRefresh ? self.$RefreshInterceptModuleExecution$(moduleObject.id) : ${
runtimeTemplate.supportsArrowFunction()
? '() => {}'
: 'function() {}'
};`,
'try {',
Template.indent(
'originalFactory.call(this, moduleObject, moduleExports, webpackRequire);'
),
'} finally {',
Template.indent(`cleanup();`),
'}',
]
)}`,
])})`,
'}',
])
}
}
// @ts-ignore webpack 5 types compat
compiler.hooks.compilation.tap('ReactFreshWebpackPlugin', (compilation) => {
injectRefreshFunctions(compilation, Template)
compilation.hooks.additionalTreeRuntimeRequirements.tap(
'ReactFreshWebpackPlugin',
(chunk: any) => {
compilation.addRuntimeModule(chunk, new ReactRefreshRuntimeModule())
}
)
})
}
class ReactFreshWebpackPlugin {
webpackMajorVersion: number
// @ts-ignore exists in webpack 5
RuntimeGlobals: typeof WebpackRuntimeGlobals
// @ts-ignore exists in webpack 5
RuntimeModule: typeof WebpackRuntimeModule
Template: typeof WebpackTemplate
constructor(
{ version, RuntimeGlobals, RuntimeModule, Template } = require('webpack')
) {
this.webpackMajorVersion = parseInt(version ?? '', 10)
this.RuntimeGlobals = RuntimeGlobals
this.RuntimeModule = RuntimeModule
this.Template = Template
}
apply(compiler: WebpackCompiler) {
switch (this.webpackMajorVersion) {
case 4: {
webpack4.call(this, compiler)
break
}
case 5: {
webpack5.call(this, compiler)
break
}
default: {
throw new Error(
`ReactFreshWebpackPlugin does not support webpack v${this.webpackMajorVersion}.`
)
}
}
}
}
export default ReactFreshWebpackPlugin