-
Notifications
You must be signed in to change notification settings - Fork 198
Expand file tree
/
Copy pathindex.js
More file actions
260 lines (237 loc) · 9.35 KB
/
index.js
File metadata and controls
260 lines (237 loc) · 9.35 KB
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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
const { validate: validateOptions } = require('schema-utils');
const { getRefreshGlobalScope } = require('./globals');
const {
getAdditionalEntries,
getIntegrationEntry,
getLibraryNamespace,
getSocketIntegration,
injectRefreshLoader,
makeRefreshRuntimeModule,
normalizeOptions,
} = require('./utils');
const schema = require('./options.json');
class ReactRefreshPlugin {
/**
* @param {import('./types').ReactRefreshPluginOptions} [options] Options for react-refresh-plugin.
*/
constructor(options = {}) {
validateOptions(/** @type {Parameters<typeof validateOptions>[0]} */ (schema), options, {
name: 'React Refresh Plugin',
baseDataPath: 'options',
});
/**
* @readonly
* @type {import('./types').NormalizedPluginOptions}
*/
this.options = normalizeOptions(options);
}
/**
* Applies the plugin.
* @param {import('webpack').Compiler} compiler A webpack compiler object.
* @returns {void}
*/
apply(compiler) {
// Skip processing in non-development mode, but allow manual force-enabling
if (
// Webpack do not set process.env.NODE_ENV, so we need to check for mode.
// Ref: https://github.com/webpack/webpack/issues/7074
(compiler.options.mode !== 'development' ||
// We also check for production process.env.NODE_ENV,
// in case it was set and mode is non-development (e.g. 'none')
(process.env.NODE_ENV && process.env.NODE_ENV === 'production')) &&
!this.options.forceEnable
) {
return;
}
const logger = compiler.getInfrastructureLogger(this.constructor.name);
// Get Webpack imports from compiler instance (if available) -
// this allow mono-repos to use different versions of Webpack without conflicts.
const webpack = compiler.webpack || require('webpack');
const {
DefinePlugin,
EntryPlugin,
ModuleFilenameHelpers,
NormalModule,
ProvidePlugin,
RuntimeGlobals,
Template,
dependencies: { ModuleDependency },
} = webpack;
// Inject react-refresh context to all Webpack entry points.
const { overlayEntries, prependEntries } = getAdditionalEntries(this.options);
// Prepended entries does not care about injection order,
// so we can utilise EntryPlugin for simpler logic.
for (const entry of prependEntries) {
new EntryPlugin(compiler.context, entry, { name: undefined }).apply(compiler);
}
/** @type {{ name?: string; index?: number }[]} */
const socketEntryData = [];
/** @type {string | undefined} */
let integrationEntry;
if (this.options.overlay && this.options.overlay.sockIntegration) {
integrationEntry = getIntegrationEntry(this.options.overlay.sockIntegration);
}
if (integrationEntry) {
compiler.hooks.make.tap(
{ name: this.constructor.name, stage: Number.POSITIVE_INFINITY },
(compilation) => {
// Exhaustively search all entries for `integrationEntry`.
// If found, mark those entries and the index of `integrationEntry`.
for (const [name, entryData] of compilation.entries.entries()) {
const index = entryData.dependencies.findIndex((dep) => {
if (!(dep instanceof ModuleDependency)) return false;
return dep.request.includes(integrationEntry);
});
if (index !== -1) {
socketEntryData.push({ name, index });
}
}
}
);
}
// Overlay entries need to be injected AFTER integration's entry,
// so we will loop through everything in `finishMake` instead of `make`.
// This ensures we can traverse all entry points and inject stuff with the correct order.
for (const [idx, entry] of overlayEntries.entries()) {
compiler.hooks.finishMake.tapPromise(
{
name: this.constructor.name,
stage: Number.MIN_SAFE_INTEGER + (overlayEntries.length - idx - 1),
},
async (compilation) => {
// Only hook into the current compiler
if (compilation.compiler !== compiler) return;
const injectData = socketEntryData.length ? socketEntryData : [{ name: undefined }];
await Promise.all(
injectData.map(({ name, index }) => {
return /** @type {Promise<void>} */ (
new Promise((resolve, reject) => {
const options = { name };
const dep = EntryPlugin.createDependency(entry, options);
compilation.addEntry(compiler.context, dep, options, (err) => {
if (err) return reject(err);
// If the entry is not a global one,
// and we have registered the index for integration entry,
// we will reorder all entry dependencies to our desired order.
// That is, to have additional entries DIRECTLY behind integration entry.
if (name && typeof index !== 'undefined') {
const entryData = compilation.entries.get(name);
if (entryData) {
entryData.dependencies.splice(
index + 1,
0,
entryData.dependencies.splice(entryData.dependencies.length - 1, 1)[0]
);
}
}
resolve();
});
})
);
})
);
}
);
}
// Inject necessary modules and variables to bundle's global scope
const refreshGlobal = getRefreshGlobalScope(RuntimeGlobals || {});
/** @type {Record<string, string | boolean>}*/
const definedModules = {
// Mapping of react-refresh globals to Webpack runtime globals
$RefreshReg$: `${refreshGlobal}.register`,
$RefreshSig$: `${refreshGlobal}.signature`,
'typeof $RefreshReg$': 'function',
'typeof $RefreshSig$': 'function',
};
/** @type {Record<string, string>} */
const providedModules = {
__react_refresh_utils__: require.resolve('./runtime/RefreshUtils'),
};
// Library mode
const libraryNamespace = getLibraryNamespace(this.options, compiler.options.output);
if (libraryNamespace) {
definedModules['__react_refresh_library__'] = JSON.stringify(
Template.toIdentifier(libraryNamespace)
);
}
if (this.options.overlay === false) {
// Stub errorOverlay module so their calls can be erased
definedModules.__react_refresh_error_overlay__ = false;
definedModules.__react_refresh_socket__ = false;
} else {
if (this.options.overlay.module) {
providedModules.__react_refresh_error_overlay__ = require.resolve(
this.options.overlay.module
);
}
if (this.options.overlay.sockIntegration) {
providedModules.__react_refresh_socket__ = getSocketIntegration(
this.options.overlay.sockIntegration
);
}
}
new DefinePlugin(definedModules).apply(compiler);
new ProvidePlugin(providedModules).apply(compiler);
/**
* @param {string} [str]
* @returns boolean
*/
const match = (str) => {
if (str == null) return false;
return ModuleFilenameHelpers.matchObject(this.options, str);
};
let loggedHotWarning = false;
compiler.hooks.compilation.tap(
this.constructor.name,
(compilation, { normalModuleFactory }) => {
// Only hook into the current compiler
if (compilation.compiler !== compiler) {
return;
}
const ReactRefreshRuntimeModule = makeRefreshRuntimeModule(webpack);
compilation.hooks.additionalTreeRuntimeRequirements.tap(
this.constructor.name,
// Setup react-refresh globals with a Webpack runtime module
(chunk, runtimeRequirements) => {
runtimeRequirements.add(RuntimeGlobals.interceptModuleExecution);
runtimeRequirements.add(RuntimeGlobals.moduleCache);
runtimeRequirements.add(refreshGlobal);
compilation.addRuntimeModule(chunk, new ReactRefreshRuntimeModule());
}
);
normalModuleFactory.hooks.afterResolve.tap(
this.constructor.name,
// Add react-refresh loader to process files that matches specified criteria
(resolveData) => {
injectRefreshLoader(resolveData.createData, {
match,
options: {
const: compilation.runtimeTemplate.supportsConst(),
esModule: this.options.esModule,
},
});
}
);
NormalModule.getCompilationHooks(compilation).loader.tap(
// `Infinity` ensures this check will run only after all other taps
{ name: this.constructor.name, stage: Infinity },
// Check for existence of the HMR runtime -
// it is the foundation to this plugin working correctly
(context) => {
if (!context.hot && !loggedHotWarning) {
logger.warn(
[
'Hot Module Replacement (HMR) is not enabled!',
'React Refresh requires HMR to function properly.',
].join(' ')
);
loggedHotWarning = true;
}
}
);
}
);
}
}
module.exports.ReactRefreshPlugin = ReactRefreshPlugin;
module.exports = ReactRefreshPlugin;