Skip to content

Commit 4acf257

Browse files
committed
fix: use __webpack_global__ in loader if available
1 parent 94732e7 commit 4acf257

2 files changed

Lines changed: 12 additions & 4 deletions

File tree

loader/index.js

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,15 +41,20 @@ function ReactRefreshLoader(source, inputSourceMap, meta) {
4141

4242
const callback = this.async();
4343

44-
const { ModuleFilenameHelpers, Template } = this._compiler.webpack || require('webpack');
44+
const { ModuleFilenameHelpers, Template, RuntimeGlobals } =
45+
this._compiler.webpack || require('webpack');
46+
47+
// When available, use `__webpack_global__` which is a stable runtime function to use `__webpack_require__` in this compilation
48+
// See: https://github.com/webpack/webpack/issues/20139
49+
const RefreshGlobals = `typeof __webpack_global__ === 'function' ? __webpack_global__ : __webpack_require__`;
4550

4651
const RefreshSetupRuntimes = {
4752
cjs: Template.asString(
48-
`__webpack_require__.$Refresh$.runtime = require('${RefreshRuntimePath}');`
53+
`${RefreshGlobals}.$Refresh$.runtime = require('${RefreshRuntimePath}');`
4954
),
5055
esm: Template.asString([
5156
`import * as __react_refresh_runtime__ from '${RefreshRuntimePath}';`,
52-
`__webpack_require__.$Refresh$.runtime = __react_refresh_runtime__;`,
57+
`${RefreshGlobals}.$Refresh$.runtime = __react_refresh_runtime__;`,
5358
]),
5459
};
5560

@@ -67,6 +72,7 @@ function ReactRefreshLoader(source, inputSourceMap, meta) {
6772
const RefreshModuleRuntime = getRefreshModuleRuntime(Template, {
6873
const: options.const,
6974
moduleSystem,
75+
refreshGlobals: RefreshGlobals,
7076
});
7177

7278
if (this.sourceMap) {

loader/utils/getRefreshModuleRuntime.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
* @typedef ModuleRuntimeOptions {Object}
33
* @property {boolean} const Use ES6 `const` and `let` in generated runtime code.
44
* @property {'cjs' | 'esm'} moduleSystem The module system to be used.
5+
* @property {string} refreshGlobals The global runtime function where React Refresh runtime is injected.
56
*/
67

78
/**
@@ -20,8 +21,9 @@ function getRefreshModuleRuntime(Template, options) {
2021
const constDeclaration = options.const ? 'const' : 'var';
2122
const letDeclaration = options.const ? 'let' : 'var';
2223
const webpackHot = options.moduleSystem === 'esm' ? 'import.meta.webpackHot' : 'module.hot';
24+
const refreshGlobals = options.refreshGlobals;
2325
return Template.asString([
24-
`${constDeclaration} $ReactRefreshModuleId$ = __webpack_require__.$Refresh$.moduleId;`,
26+
`${constDeclaration} $ReactRefreshModuleId$ = ${refreshGlobals}.$Refresh$.moduleId;`,
2527
`${constDeclaration} $ReactRefreshCurrentExports$ = __react_refresh_utils__.getModuleExports(`,
2628
Template.indent('$ReactRefreshModuleId$'),
2729
');',

0 commit comments

Comments
 (0)