0
# Environment System
1
2
Multi-environment build support allowing simultaneous builds for different targets with environment-specific configurations. Enables building for web, Node.js, and web workers with distinct settings and optimizations.
3
4
## Capabilities
5
6
### Environment Configuration
7
8
Define environment-specific configurations for different build targets.
9
10
```typescript { .api }
11
/**
12
* Environment-specific configuration interface
13
*/
14
interface EnvironmentConfig {
15
/** Source code configuration for this environment */
16
source?: SourceConfig;
17
/** Build output configuration for this environment */
18
output?: OutputConfig;
19
/** HTML generation configuration for this environment */
20
html?: HtmlConfig;
21
/** Build tools configuration for this environment */
22
tools?: ToolsConfig;
23
/** Development configuration for this environment */
24
dev?: DevConfig;
25
/** Server configuration for this environment */
26
server?: ServerConfig;
27
/** Security configuration for this environment */
28
security?: SecurityConfig;
29
/** Performance configuration for this environment */
30
performance?: PerformanceConfig;
31
/** Module Federation configuration for this environment */
32
moduleFederation?: ModuleFederationConfig;
33
}
34
35
/**
36
* Main configuration with environments
37
*/
38
interface RsbuildConfig {
39
/** Environment-specific configurations */
40
environments?: Record<string, EnvironmentConfig>;
41
// ... other global config properties
42
}
43
```
44
45
**Usage Examples:**
46
47
```typescript
48
import { defineConfig } from "@rsbuild/core";
49
50
// Multi-environment configuration
51
export default defineConfig({
52
// Global configuration applies to all environments
53
source: {
54
alias: {
55
"@": "./src",
56
"@utils": "./src/utils",
57
},
58
},
59
60
// Environment-specific configurations
61
environments: {
62
// Web environment for browser
63
web: {
64
output: {
65
target: "web",
66
assetPrefix: "/static/",
67
},
68
html: {
69
template: "./src/web.html",
70
title: "Web App",
71
},
72
performance: {
73
chunkSplit: {
74
strategy: "split-by-experience",
75
},
76
},
77
},
78
79
// Node.js environment for server-side
80
node: {
81
output: {
82
target: "node",
83
filename: {
84
js: "[name].cjs",
85
},
86
},
87
tools: {
88
rspack: {
89
externals: {
90
express: "commonjs express",
91
},
92
},
93
},
94
},
95
96
// Web worker environment
97
worker: {
98
output: {
99
target: "web-worker",
100
},
101
source: {
102
entry: {
103
worker: "./src/worker.ts",
104
},
105
},
106
},
107
108
// Mobile-optimized web environment
109
mobile: {
110
output: {
111
target: "web",
112
assetPrefix: "https://cdn.example.com/mobile/",
113
},
114
performance: {
115
chunkSplit: {
116
strategy: "all-in-one",
117
},
118
removeConsole: true,
119
},
120
html: {
121
template: "./src/mobile.html",
122
meta: {
123
viewport: "width=device-width, initial-scale=1.0, user-scalable=no",
124
},
125
},
126
},
127
},
128
});
129
```
130
131
### Environment Context
132
133
Runtime context information provided to plugins and hooks for each environment.
134
135
```typescript { .api }
136
/**
137
* Environment context provided during build process
138
*/
139
interface EnvironmentContext {
140
/** Environment name */
141
name: string;
142
/** Environment index in build order */
143
index: number;
144
/** Entry point configuration */
145
entry: RsbuildEntry;
146
/** HTML file paths mapping */
147
htmlPaths: Record<string, string>;
148
/** Output directory path */
149
distPath: string;
150
/** Browser compatibility targets */
151
browserslist: string[];
152
/** Normalized environment configuration */
153
config: NormalizedEnvironmentConfig;
154
/** WebSocket token for dev server */
155
webSocketToken: string;
156
}
157
158
/**
159
* Normalized environment configuration with defaults applied
160
*/
161
interface NormalizedEnvironmentConfig {
162
source: NormalizedSourceConfig;
163
output: NormalizedOutputConfig;
164
html: NormalizedHtmlConfig;
165
tools: NormalizedToolsConfig;
166
dev: NormalizedDevConfig;
167
server: NormalizedServerConfig;
168
security: NormalizedSecurityConfig;
169
performance: NormalizedPerformanceConfig;
170
moduleFederation: NormalizedModuleFederationConfig;
171
}
172
```
173
174
### Environment-Specific Hooks
175
176
Hooks that receive environment context for environment-aware processing.
177
178
```typescript { .api }
179
/**
180
* Hook called before compilation for each environment
181
*/
182
type OnBeforeEnvironmentCompileFn = (params: {
183
environment: EnvironmentContext;
184
}) => void | Promise<void>;
185
186
/**
187
* Hook called after compilation for each environment
188
*/
189
type OnAfterEnvironmentCompileFn = (params: {
190
environment: EnvironmentContext;
191
stats: any;
192
}) => void | Promise<void>;
193
```
194
195
**Hook Usage Examples:**
196
197
```typescript
198
const multiEnvPlugin = (): RsbuildPlugin => ({
199
name: "multi-env-plugin",
200
setup(api) {
201
api.onBeforeEnvironmentCompile(({ environment }) => {
202
console.log(`Starting compilation for ${environment.name}`);
203
204
// Environment-specific logic
205
if (environment.name === "node") {
206
console.log("Configuring for Node.js target");
207
} else if (environment.name === "web") {
208
console.log("Configuring for web target");
209
}
210
});
211
212
api.onAfterEnvironmentCompile(({ environment, stats }) => {
213
console.log(`Completed compilation for ${environment.name}`);
214
215
if (stats.hasErrors()) {
216
console.error(`Errors in ${environment.name} build`);
217
}
218
});
219
},
220
});
221
```
222
223
### Environment-Aware Configuration
224
225
Modify configuration based on environment context.
226
227
```typescript { .api }
228
/**
229
* Modify environment configuration hook
230
*/
231
type ModifyEnvironmentConfigFn = (
232
config: EnvironmentConfig,
233
utils: ModifyEnvironmentConfigUtils
234
) => EnvironmentConfig | void | Promise<EnvironmentConfig | void>;
235
236
interface ModifyEnvironmentConfigUtils {
237
/** Environment name */
238
name: string;
239
/** Configuration merging utility */
240
mergeConfig: (config: EnvironmentConfig) => EnvironmentConfig;
241
}
242
```
243
244
**Configuration Examples:**
245
246
```typescript
247
const envConfigPlugin = (): RsbuildPlugin => ({
248
name: "env-config-plugin",
249
setup(api) {
250
api.modifyEnvironmentConfig((config, { name, mergeConfig }) => {
251
// Environment-specific modifications
252
switch (name) {
253
case "web":
254
return mergeConfig(config, {
255
output: {
256
assetPrefix: "/web-assets/",
257
},
258
performance: {
259
bundleAnalyze: process.env.ANALYZE === "true",
260
},
261
});
262
263
case "node":
264
return mergeConfig(config, {
265
output: {
266
externals: {
267
// Mark Node.js modules as external
268
fs: "commonjs fs",
269
path: "commonjs path",
270
os: "commonjs os",
271
},
272
},
273
});
274
275
case "mobile":
276
return mergeConfig(config, {
277
performance: {
278
removeConsole: true,
279
chunkSplit: {
280
strategy: "all-in-one",
281
},
282
},
283
});
284
285
default:
286
return config;
287
}
288
});
289
},
290
});
291
```
292
293
### Build Target Types
294
295
```typescript { .api }
296
/**
297
* Available build targets
298
*/
299
type RsbuildTarget = 'web' | 'node' | 'web-worker';
300
301
/**
302
* Target-specific configuration
303
*/
304
interface OutputConfig {
305
/** Build target platform(s) */
306
target?: RsbuildTarget | RsbuildTarget[];
307
// ... other output options
308
}
309
```
310
311
**Target Characteristics:**
312
313
- **`web`**: Browser environment with DOM, Web APIs, and module loading
314
- **`node`**: Node.js environment with Node.js APIs and CommonJS modules
315
- **`web-worker`**: Web Worker environment with limited APIs and no DOM
316
317
### Environment Selection
318
319
Control which environments to build during development or production.
320
321
```typescript { .api }
322
interface CreateRsbuildOptions {
323
/** Specific environments to build */
324
environment?: string[];
325
// ... other options
326
}
327
```
328
329
**Usage Examples:**
330
331
```typescript
332
// Build only specific environments
333
const rsbuild = await createRsbuild({
334
rsbuildConfig: config,
335
environment: ["web", "mobile"], // Only build web and mobile
336
});
337
338
// Build all environments (default)
339
const rsbuildAll = await createRsbuild({
340
rsbuildConfig: config,
341
// Builds all defined environments
342
});
343
344
// Environment-specific development
345
if (process.env.TARGET === "mobile") {
346
rsbuild = await createRsbuild({
347
rsbuildConfig: config,
348
environment: ["mobile"],
349
});
350
}
351
```
352
353
### Environment-Specific Entry Points
354
355
Different entry points for different environments.
356
357
```typescript { .api }
358
export default defineConfig({
359
environments: {
360
web: {
361
source: {
362
entry: {
363
index: "./src/web/index.ts",
364
about: "./src/web/about.ts",
365
},
366
},
367
},
368
369
node: {
370
source: {
371
entry: {
372
server: "./src/server/index.ts",
373
worker: "./src/server/worker.ts",
374
},
375
},
376
},
377
378
worker: {
379
source: {
380
entry: {
381
"service-worker": "./src/workers/service-worker.ts",
382
"web-worker": "./src/workers/web-worker.ts",
383
},
384
},
385
},
386
},
387
});
388
```
389
390
### Environment-Specific HTML
391
392
Different HTML templates and configurations per environment.
393
394
```typescript { .api }
395
export default defineConfig({
396
environments: {
397
web: {
398
html: {
399
template: "./src/templates/web.html",
400
title: "Web Application",
401
meta: {
402
description: "Full-featured web application",
403
},
404
},
405
},
406
407
mobile: {
408
html: {
409
template: "./src/templates/mobile.html",
410
title: "Mobile App",
411
meta: {
412
viewport: "width=device-width, initial-scale=1.0, user-scalable=no",
413
"mobile-web-app-capable": "yes",
414
},
415
},
416
},
417
418
// Node.js environments typically don't need HTML
419
node: {
420
html: false, // Disable HTML generation
421
},
422
},
423
});
424
```
425
426
### Performance Optimization by Environment
427
428
Environment-specific performance optimizations.
429
430
```typescript { .api }
431
export default defineConfig({
432
environments: {
433
web: {
434
performance: {
435
chunkSplit: {
436
strategy: "split-by-experience",
437
},
438
preload: true,
439
prefetch: true,
440
},
441
},
442
443
mobile: {
444
performance: {
445
chunkSplit: {
446
strategy: "all-in-one", // Single bundle for mobile
447
},
448
removeConsole: true,
449
bundleAnalyze: false,
450
},
451
},
452
453
node: {
454
performance: {
455
chunkSplit: {
456
strategy: "all-in-one", // Single server bundle
457
},
458
removeConsole: false, // Keep console for server logging
459
},
460
},
461
},
462
});
463
```
464
465
### Development Server per Environment
466
467
Environment-specific development server configuration.
468
469
```typescript { .api }
470
export default defineConfig({
471
environments: {
472
web: {
473
server: {
474
port: 3000,
475
open: true,
476
},
477
dev: {
478
hmr: true,
479
},
480
},
481
482
mobile: {
483
server: {
484
port: 3001,
485
host: "0.0.0.0", // Allow mobile device access
486
},
487
dev: {
488
client: {
489
overlay: {
490
warnings: false, // Less intrusive on mobile
491
},
492
},
493
},
494
},
495
496
// Node.js environments typically don't need dev server
497
node: {
498
server: false, // Disable dev server
499
},
500
},
501
});
502
```