0
# Configuration Management
1
2
Configuration loading, definition, and merging utilities for Rsbuild. Handles both file-based and programmatic configuration with TypeScript support and environment-specific settings.
3
4
## Capabilities
5
6
### Define Configuration
7
8
Type-safe configuration helper function that provides IntelliSense and type checking for Rsbuild configurations.
9
10
```typescript { .api }
11
/**
12
* Type-safe configuration helper with IntelliSense support
13
* @param config - Rsbuild configuration object or function
14
* @returns The same configuration for use with createRsbuild
15
*/
16
function defineConfig(config: RsbuildConfigExport): RsbuildConfigExport;
17
18
type RsbuildConfigExport =
19
| RsbuildConfig
20
| RsbuildConfigSyncFn
21
| RsbuildConfigAsyncFn;
22
23
type RsbuildConfigSyncFn = (env: ConfigParams) => RsbuildConfig;
24
type RsbuildConfigAsyncFn = (env: ConfigParams) => Promise<RsbuildConfig>;
25
26
interface ConfigParams {
27
/** Current environment mode */
28
env: string;
29
/** CLI command being executed */
30
command: string;
31
/** Environment mode override */
32
envMode?: string;
33
/** Custom metadata passed to config */
34
meta?: Record<string, unknown>;
35
}
36
```
37
38
**Usage Examples:**
39
40
```typescript
41
import { defineConfig } from "@rsbuild/core";
42
43
// Static configuration
44
export default defineConfig({
45
source: {
46
entry: {
47
index: "./src/index.ts",
48
},
49
},
50
output: {
51
target: "web",
52
},
53
});
54
55
// Dynamic configuration with environment
56
export default defineConfig(({ env, command }) => {
57
const isDev = env === "development";
58
59
return {
60
source: {
61
entry: {
62
index: "./src/index.ts",
63
},
64
},
65
output: {
66
target: "web",
67
minify: !isDev,
68
},
69
dev: {
70
hmr: isDev,
71
},
72
};
73
});
74
75
// Async configuration
76
export default defineConfig(async ({ env }) => {
77
const apiConfig = await fetchConfigFromAPI(env);
78
79
return {
80
source: {
81
entry: apiConfig.entries,
82
},
83
output: {
84
target: apiConfig.target,
85
},
86
};
87
});
88
```
89
90
### Load Configuration File
91
92
Loads Rsbuild configuration from file with support for TypeScript, ESM, and CommonJS formats.
93
94
```typescript { .api }
95
/**
96
* Load Rsbuild configuration from file
97
* @param options - Configuration loading options
98
* @returns Promise resolving to loaded configuration result
99
*/
100
function loadConfig(options?: LoadConfigOptions): Promise<LoadConfigResult>;
101
102
interface LoadConfigOptions {
103
/** Root path for config file resolution */
104
cwd?: string;
105
/** Specific config file path (relative or absolute) */
106
path?: string;
107
/** Custom metadata to pass to config function */
108
meta?: Record<string, unknown>;
109
/** Environment mode for config function */
110
envMode?: string;
111
/** Configuration loader to use */
112
configLoader?: 'jiti' | 'native';
113
}
114
115
interface LoadConfigResult {
116
/** Loaded configuration object */
117
config: RsbuildConfig;
118
/** Path to the loaded config file */
119
filePath?: string;
120
/** Environment variables loaded with config */
121
loadedEnv?: Record<string, string>;
122
}
123
```
124
125
**Default Config File Resolution:**
126
127
Rsbuild searches for config files in this order:
128
1. `rsbuild.config.ts`
129
2. `rsbuild.config.js`
130
3. `rsbuild.config.mjs`
131
4. `rsbuild.config.mts`
132
5. `rsbuild.config.cts`
133
6. `rsbuild.config.cjs`
134
135
**Usage Examples:**
136
137
```typescript
138
import { loadConfig } from "@rsbuild/core";
139
140
// Load from default location
141
const { config } = await loadConfig();
142
143
// Load from specific file
144
const { config, filePath } = await loadConfig({
145
path: "./config/rsbuild.prod.config.ts",
146
});
147
148
// Load with custom working directory
149
const { config } = await loadConfig({
150
cwd: "/path/to/project",
151
});
152
153
// Load with custom metadata
154
const { config } = await loadConfig({
155
meta: {
156
buildId: "12345",
157
deployEnv: "staging",
158
},
159
});
160
161
// Use native Node.js loader (requires Node.js >= 22.6)
162
const { config } = await loadConfig({
163
configLoader: "native",
164
});
165
```
166
167
### Merge Configurations
168
169
Merges multiple Rsbuild configuration objects with deep merging and array handling.
170
171
```typescript { .api }
172
/**
173
* Merge multiple Rsbuild configurations with deep merging
174
* @param configs - Configuration objects to merge
175
* @returns Merged configuration object
176
*/
177
function mergeRsbuildConfig(...configs: RsbuildConfig[]): RsbuildConfig;
178
```
179
180
**Merge Behavior:**
181
- Objects are deeply merged
182
- Arrays are concatenated
183
- Later values override earlier ones for primitives
184
- Plugins arrays are merged and deduplicated by name
185
186
**Usage Examples:**
187
188
```typescript
189
import { mergeRsbuildConfig } from "@rsbuild/core";
190
191
const baseConfig = {
192
source: {
193
entry: { index: "./src/index.ts" },
194
alias: { "@": "./src" },
195
},
196
output: {
197
target: "web",
198
},
199
};
200
201
const devConfig = {
202
dev: {
203
hmr: true,
204
},
205
output: {
206
sourceMap: true,
207
},
208
};
209
210
const prodConfig = {
211
output: {
212
minify: true,
213
sourceMap: false,
214
},
215
performance: {
216
chunkSplit: {
217
strategy: "split-by-experience",
218
},
219
},
220
};
221
222
// Merge configurations
223
const developmentConfig = mergeRsbuildConfig(baseConfig, devConfig);
224
const productionConfig = mergeRsbuildConfig(baseConfig, prodConfig);
225
226
// Merge multiple configs
227
const finalConfig = mergeRsbuildConfig(
228
baseConfig,
229
environmentConfig,
230
featureConfig,
231
userConfig
232
);
233
```
234
235
## Configuration Structure
236
237
### Main Configuration Interface
238
239
```typescript { .api }
240
interface RsbuildConfig {
241
/** Build mode */
242
mode?: 'development' | 'production' | 'none';
243
/** Project root directory */
244
root?: string;
245
/** Logging level */
246
logLevel?: 'silent' | 'error' | 'warn' | 'info' | 'debug';
247
/** Environment-specific configurations */
248
environments?: Record<string, EnvironmentConfig>;
249
/** Source code configuration */
250
source?: SourceConfig;
251
/** Build output configuration */
252
output?: OutputConfig;
253
/** HTML generation configuration */
254
html?: HtmlConfig;
255
/** Build tools configuration */
256
tools?: ToolsConfig;
257
/** Development configuration */
258
dev?: DevConfig;
259
/** Development server configuration */
260
server?: ServerConfig;
261
/** Security configuration */
262
security?: SecurityConfig;
263
/** Performance optimization configuration */
264
performance?: PerformanceConfig;
265
/** Module Federation configuration */
266
moduleFederation?: ModuleFederationConfig;
267
/** Plugin list */
268
plugins?: RsbuildPlugins;
269
/** Bundler provider configuration */
270
provider?: unknown;
271
}
272
```
273
274
### Source Configuration
275
276
```typescript { .api }
277
interface SourceConfig {
278
/** Entry points configuration */
279
entry?: RsbuildEntry;
280
/** Module path aliases */
281
alias?: Record<string, string | false> | ((aliases: Record<string, string>) => Record<string, string>);
282
/** Global variable definitions */
283
define?: Record<string, string | boolean | undefined>;
284
/** Files to include in compilation */
285
include?: (string | RegExp)[];
286
/** Files to exclude from compilation */
287
exclude?: (string | RegExp)[];
288
/** TypeScript decorator configuration */
289
decorators?: {
290
version?: '2018-09' | 'legacy';
291
metadata?: boolean;
292
};
293
/** Import transformation rules */
294
transformImport?: TransformImport[];
295
}
296
297
interface TransformImport {
298
libraryName: string;
299
libraryDirectory?: string;
300
style?: boolean | string;
301
styleLibraryDirectory?: string;
302
camel2DashComponentName?: boolean;
303
camel2UnderlineComponentName?: boolean;
304
transformToDefaultImport?: boolean;
305
}
306
307
type RsbuildEntry = string | string[] | Record<string, string | string[] | RsbuildEntryDescription>;
308
309
interface RsbuildEntryDescription {
310
import: string | string[];
311
filename?: string;
312
runtime?: string;
313
publicPath?: string;
314
}
315
```
316
317
### Output Configuration
318
319
```typescript { .api }
320
interface OutputConfig {
321
/** Build target platform */
322
target?: RsbuildTarget | RsbuildTarget[];
323
/** Output directory paths */
324
distPath?: DistPathConfig;
325
/** Output file naming patterns */
326
filename?: FilenameConfig;
327
/** Source map generation */
328
sourceMap?: SourceMap;
329
/** Code minification settings */
330
minify?: Minify;
331
/** Polyfill injection */
332
polyfill?: Polyfill;
333
/** External dependencies */
334
externals?: Externals;
335
/** Asset URL prefix */
336
assetPrefix?: string | ((params: { target: RsbuildTarget; environment: string }) => string);
337
/** Output charset */
338
charset?: 'ascii' | 'utf8';
339
/** Clean output directory */
340
cleanDistPath?: boolean | CleanDistPathObject;
341
/** File copying configuration */
342
copy?: CopyConfig[];
343
/** Data URI size limits */
344
dataUriLimit?: DataUriLimit;
345
/** Legal comment handling */
346
legalComments?: 'none' | 'inline' | 'linked';
347
}
348
349
type RsbuildTarget = 'web' | 'node' | 'web-worker';
350
type SourceMap = boolean | 'inline' | 'hidden';
351
type Minify = boolean | 'terser' | 'swc' | 'esbuild';
352
type Polyfill = 'entry' | 'usage' | 'off';
353
354
interface DistPathConfig {
355
root?: string;
356
js?: string;
357
css?: string;
358
svg?: string;
359
font?: string;
360
html?: string;
361
image?: string;
362
media?: string;
363
worker?: string;
364
}
365
366
interface FilenameConfig {
367
js?: string;
368
css?: string;
369
svg?: string;
370
font?: string;
371
image?: string;
372
media?: string;
373
}
374
```
375
376
### Development Configuration
377
378
```typescript { .api }
379
interface DevConfig {
380
/** Hot Module Replacement */
381
hmr?: boolean | HMROptions;
382
/** Live reload on file changes */
383
liveReload?: boolean;
384
/** Asset prefix for development */
385
assetPrefix?: string | 'auto';
386
/** Client-side configuration */
387
client?: ClientConfig;
388
/** Progress bar display */
389
progressBar?: boolean | ProgressBarConfig;
390
/** Lazy compilation settings */
391
lazyCompilation?: boolean | LazyCompilationOptions;
392
}
393
394
interface HMROptions {
395
port?: number;
396
host?: string;
397
path?: string;
398
}
399
400
interface ClientConfig {
401
protocol?: 'ws' | 'wss';
402
port?: number;
403
host?: string;
404
path?: string;
405
overlay?: boolean | OverlayOptions;
406
}
407
408
interface OverlayOptions {
409
errors?: boolean;
410
warnings?: boolean;
411
}
412
```
413
414
### Server Configuration
415
416
```typescript { .api }
417
interface ServerConfig {
418
/** Server port */
419
port?: number;
420
/** Server host */
421
host?: string;
422
/** HTTPS configuration */
423
https?: boolean | HTTPSOptions;
424
/** Proxy configuration */
425
proxy?: ProxyConfig;
426
/** CORS settings */
427
cors?: boolean | CorsOptions;
428
/** Custom response headers */
429
headers?: Record<string, string>;
430
/** History API fallback for SPAs */
431
historyApiFallback?: boolean | HistoryApiFallbackOptions;
432
/** Response compression */
433
compress?: boolean | CompressOptions;
434
/** Auto-open browser */
435
open?: boolean | string | OpenOptions;
436
/** Base URL path */
437
base?: string;
438
/** Static file serving */
439
publicDir?: PublicDir;
440
/** Custom middleware setup */
441
setupMiddlewares?: SetupMiddlewaresFn;
442
}
443
444
interface HTTPSOptions {
445
key?: string;
446
cert?: string;
447
}
448
449
interface ProxyConfig {
450
[path: string]: string | ProxyOptions;
451
}
452
453
interface ProxyOptions {
454
target: string;
455
changeOrigin?: boolean;
456
pathRewrite?: Record<string, string>;
457
onProxyReq?: Function;
458
onProxyRes?: Function;
459
}
460
```
461
462
### Performance Configuration
463
464
```typescript { .api }
465
interface PerformanceConfig {
466
/** Bundle analysis */
467
bundleAnalyze?: BundleAnalyzeOptions;
468
/** Code splitting strategy */
469
chunkSplit?: ChunkSplitOptions;
470
/** Resource preloading */
471
preload?: boolean | PreloadOptions;
472
/** Resource prefetching */
473
prefetch?: boolean | PrefetchOptions;
474
/** DNS preconnection */
475
preconnect?: PreconnectOption[];
476
/** DNS prefetching */
477
dnsPrefetch?: string[];
478
/** Console removal in production */
479
removeConsole?: boolean | RemoveConsoleOptions;
480
/** Remove Moment.js locales */
481
removeMomentLocale?: boolean;
482
/** Build caching */
483
buildCache?: boolean | BuildCacheOptions;
484
}
485
486
interface ChunkSplitOptions {
487
strategy?: 'split-by-experience' | 'split-by-module' | 'all-in-one' | 'single-vendor';
488
minSize?: number;
489
maxSize?: number;
490
chunks?: 'async' | 'initial' | 'all';
491
enforce?: boolean;
492
cacheGroups?: Record<string, CacheGroupOptions>;
493
}
494
```
495
496
## Environment-Specific Configuration
497
498
```typescript { .api }
499
interface EnvironmentConfig {
500
/** Source configuration for this environment */
501
source?: SourceConfig;
502
/** Output configuration for this environment */
503
output?: OutputConfig;
504
/** HTML configuration for this environment */
505
html?: HtmlConfig;
506
/** Tools configuration for this environment */
507
tools?: ToolsConfig;
508
/** Development configuration for this environment */
509
dev?: DevConfig;
510
/** Server configuration for this environment */
511
server?: ServerConfig;
512
/** Security configuration for this environment */
513
security?: SecurityConfig;
514
/** Performance configuration for this environment */
515
performance?: PerformanceConfig;
516
/** Module Federation configuration for this environment */
517
moduleFederation?: ModuleFederationConfig;
518
}
519
```
520
521
**Usage Examples:**
522
523
```typescript
524
export default defineConfig({
525
// Global configuration
526
source: {
527
alias: {
528
"@": "./src",
529
},
530
},
531
532
// Environment-specific configurations
533
environments: {
534
web: {
535
output: {
536
target: "web",
537
},
538
html: {
539
template: "./src/web.html",
540
},
541
},
542
543
node: {
544
output: {
545
target: "node",
546
},
547
tools: {
548
rspack: {
549
externals: nodeExternals(),
550
},
551
},
552
},
553
554
mobile: {
555
output: {
556
target: "web",
557
assetPrefix: "https://cdn.example.com/mobile/",
558
},
559
performance: {
560
chunkSplit: {
561
strategy: "all-in-one",
562
},
563
},
564
},
565
},
566
});
567
```