0
# Loader Configuration
1
2
The ReactRefreshLoader injects React Refresh HMR code into JavaScript and TypeScript modules, enabling Fast Refresh functionality at the module level.
3
4
## Capabilities
5
6
### ReactRefreshLoader Function
7
8
Webpack loader that processes module source code to inject React Refresh runtime.
9
10
```javascript { .api }
11
/**
12
* A simple Webpack loader to inject react-refresh HMR code into modules.
13
* @this {import('webpack').LoaderContext<ReactRefreshLoaderOptions>}
14
* @param {string} source The original module source code.
15
* @param {import('source-map').RawSourceMap} [inputSourceMap] The source map of the module.
16
* @param {*} [meta] The loader metadata passed in.
17
* @returns {void}
18
*/
19
function ReactRefreshLoader(
20
this: import('webpack').LoaderContext<ReactRefreshLoaderOptions>,
21
source: string,
22
inputSourceMap?: import('source-map').RawSourceMap,
23
meta?: any
24
): void;
25
```
26
27
### Loader Usage
28
29
Configure the loader in your Webpack configuration:
30
31
```javascript
32
// webpack.config.js
33
module.exports = {
34
module: {
35
rules: [
36
{
37
test: /\.[jt]sx?$/,
38
exclude: /node_modules/,
39
use: [
40
{
41
loader: '@pmmmwh/react-refresh-webpack-plugin/loader',
42
options: {
43
const: true,
44
esModule: false
45
}
46
},
47
// Other loaders like babel-loader
48
'babel-loader'
49
],
50
},
51
],
52
},
53
};
54
```
55
56
### Loader Options
57
58
Configuration interface for customizing loader behavior.
59
60
```javascript { .api }
61
interface ReactRefreshLoaderOptions {
62
/**
63
* Enables usage of ES6 `const` and `let` in generated runtime code.
64
*/
65
const?: boolean;
66
67
/**
68
* Enables strict ES Modules compatible runtime.
69
*/
70
esModule?: boolean | ESModuleOptions;
71
}
72
```
73
74
### Const Option
75
76
Controls whether ES6 `const` and `let` keywords are used in generated runtime code.
77
78
```javascript { .api }
79
const?: boolean;
80
```
81
82
**Usage Examples:**
83
84
```javascript
85
// Enable modern syntax (recommended)
86
{
87
loader: '@pmmmwh/react-refresh-webpack-plugin/loader',
88
options: {
89
const: true
90
}
91
}
92
93
// Use legacy var declarations for older environments
94
{
95
loader: '@pmmmwh/react-refresh-webpack-plugin/loader',
96
options: {
97
const: false
98
}
99
}
100
```
101
102
**Default:** Determined by Webpack's `compilation.runtimeTemplate.supportsConst()`
103
104
### ES Module Option
105
106
Configures ES Modules compatibility for the refresh runtime at the loader level.
107
108
```javascript { .api }
109
esModule?: boolean | ESModuleOptions;
110
111
interface ESModuleOptions {
112
/**
113
* Files to explicitly exclude from flagged as ES Modules.
114
*/
115
exclude?: string | RegExp | (string | RegExp)[];
116
117
/**
118
* Files to explicitly include for flagged as ES Modules.
119
*/
120
include?: string | RegExp | (string | RegExp)[];
121
}
122
```
123
124
**Usage Examples:**
125
126
```javascript
127
// Enable ES Modules for all processed files
128
{
129
loader: '@pmmmwh/react-refresh-webpack-plugin/loader',
130
options: {
131
esModule: true
132
}
133
}
134
135
// Conditional ES Module usage
136
{
137
loader: '@pmmmwh/react-refresh-webpack-plugin/loader',
138
options: {
139
esModule: {
140
include: /\.mjs$/,
141
exclude: /legacy/
142
}
143
}
144
}
145
```
146
147
**Default:** Auto-detection based on module system
148
149
### Normalized Loader Options
150
151
Internal interface representing processed loader options after normalization.
152
153
```javascript { .api }
154
interface NormalizedLoaderOptions {
155
/**
156
* Enables usage of ES6 `const` and `let` in generated runtime code.
157
*/
158
const: boolean;
159
160
/**
161
* Enables strict ES Modules compatible runtime.
162
*/
163
esModule?: boolean | ESModuleOptions;
164
}
165
```
166
167
### Module System Detection
168
169
The loader automatically detects the module system being used:
170
171
```javascript { .api }
172
/** @type {'esm' | 'cjs'} */
173
type ModuleSystem = 'esm' | 'cjs';
174
```
175
176
**Detection Logic:**
177
1. Check `package.json` `type` field (`"module"` → ESM, `"commonjs"` → CJS)
178
2. Check file extension (`.mjs` → ESM, `.cjs` → CJS)
179
3. Analyze import/export statements in source code
180
4. Fall back to CommonJS if undetermined
181
182
### Source Map Support
183
184
The loader preserves and generates source maps for debugging:
185
186
**Features:**
187
- Preserves existing source maps from previous loaders
188
- Generates identity source maps when none exist
189
- Maintains accurate line/column mappings after code injection
190
- Works with Webpack's source map options
191
192
**Usage:**
193
194
```javascript
195
// webpack.config.js
196
module.exports = {
197
devtool: 'eval-source-map', // Enable source maps
198
module: {
199
rules: [
200
{
201
test: /\.[jt]sx?$/,
202
use: [
203
'@pmmmwh/react-refresh-webpack-plugin/loader',
204
'babel-loader'
205
]
206
}
207
]
208
}
209
};
210
```
211
212
### Generated Runtime Code
213
214
The loader injects runtime setup and module refresh code:
215
216
**CommonJS Example:**
217
```javascript
218
// Injected at module start
219
__webpack_require__.$Refresh$.runtime = require('react-refresh');
220
221
// Original module code...
222
223
// Injected at module end
224
if (module.hot) {
225
module.hot.accept();
226
$RefreshReg$(Component, 'ComponentName');
227
}
228
```
229
230
**ES Module Example:**
231
```javascript
232
// Injected at module start
233
import * as __react_refresh_runtime__ from 'react-refresh';
234
__webpack_require__.$Refresh$.runtime = __react_refresh_runtime__;
235
236
// Original module code...
237
238
// Injected at module end
239
if (import.meta.webpackHot) {
240
import.meta.webpackHot.accept();
241
$RefreshReg$(Component, 'ComponentName');
242
}
243
```
244
245
### Options Validation
246
247
The loader validates options using a JSON schema:
248
249
**Schema Location:** `loader/options.json`
250
251
**Validation Error Example:**
252
```javascript
253
// Invalid loader configuration
254
{
255
loader: '@pmmmwh/react-refresh-webpack-plugin/loader',
256
options: {
257
invalidOption: 'value' // Will cause validation error
258
}
259
}
260
```
261
262
### Loader Utilities
263
264
The loader provides utility functions for advanced integration scenarios.
265
266
```javascript { .api }
267
const {
268
getIdentitySourceMap,
269
getModuleSystem,
270
getRefreshModuleRuntime,
271
normalizeOptions,
272
} = require('@pmmmwh/react-refresh-webpack-plugin/loader/utils');
273
274
/**
275
* Creates an identity source map for a source file
276
* @param {string} source - Source code content
277
* @param {string} filename - Source file path
278
* @returns {import('source-map').RawSourceMap} - Identity source map
279
*/
280
function getIdentitySourceMap(source: string, filename: string): RawSourceMap;
281
282
/**
283
* Determines the module system used by a file
284
* @param {object} ModuleFilenameHelpers - Webpack filename helpers
285
* @param {NormalizedLoaderOptions} options - Normalized loader options
286
* @returns {Promise<'esm' | 'cjs'>} - Module system type
287
*/
288
function getModuleSystem(
289
ModuleFilenameHelpers: any,
290
options: NormalizedLoaderOptions
291
): Promise<'esm' | 'cjs'>;
292
293
/**
294
* Generates React Refresh module runtime code
295
* @param {object} Template - Webpack template utilities
296
* @param {object} config - Runtime configuration
297
* @returns {string} - Generated runtime code
298
*/
299
function getRefreshModuleRuntime(
300
Template: any,
301
config: { const: boolean; moduleSystem: 'esm' | 'cjs' }
302
): string;
303
304
/**
305
* Normalizes loader options with defaults
306
* @param {ReactRefreshLoaderOptions} options - Raw loader options
307
* @returns {NormalizedLoaderOptions} - Normalized options
308
*/
309
function normalizeOptions(options: ReactRefreshLoaderOptions): NormalizedLoaderOptions;
310
```
311
312
### Loader Context Requirements
313
314
The loader requires specific Webpack context:
315
316
- **Webpack Version:** 5.2.0+
317
- **Hot Module Replacement:** Must be enabled
318
- **Module Rules:** Should target React component files
319
- **Babel Integration:** Requires `react-refresh/babel` plugin
320
321
**Warning Handling:**
322
```javascript
323
// The loader will warn if HMR is not enabled
324
if (!context.hot) {
325
logger.warn(
326
'Hot Module Replacement (HMR) is not enabled! ' +
327
'React Refresh requires HMR to function properly.'
328
);
329
}
330
```