0
# Development Server
1
2
Development server functionality with hot module replacement, live reload, proxy support, and debugging capabilities. Provides fast development experience with automatic recompilation and browser refresh.
3
4
## Capabilities
5
6
### Development Server Interface
7
8
Core development server functionality for local development.
9
10
```typescript { .api }
11
/**
12
* Development server instance with lifecycle management
13
*/
14
interface RsbuildDevServer {
15
/** Start listening on configured port */
16
listen(): Promise<void>;
17
/** Close the development server */
18
close(): Promise<void>;
19
/** Connect server instance */
20
server: Connect.Server;
21
/** Server port number */
22
port: number;
23
/** Server host address */
24
host: string;
25
}
26
27
/**
28
* Result of starting development server
29
*/
30
interface StartServerResult {
31
/** Server URLs (local and network) */
32
urls: string[];
33
/** Server port number */
34
port: number;
35
/** Development server instance */
36
server: RsbuildDevServer;
37
}
38
```
39
40
### Server Configuration
41
42
```typescript { .api }
43
interface ServerConfig {
44
/** Server port number */
45
port?: number;
46
/** Server host address */
47
host?: string;
48
/** HTTPS configuration */
49
https?: boolean | HTTPSOptions;
50
/** Proxy configuration for API calls */
51
proxy?: ProxyConfig;
52
/** CORS settings */
53
cors?: boolean | CorsOptions;
54
/** Custom response headers */
55
headers?: Record<string, string>;
56
/** SPA routing support */
57
historyApiFallback?: boolean | HistoryApiFallbackOptions;
58
/** Response compression */
59
compress?: boolean | CompressOptions;
60
/** Auto-open browser */
61
open?: boolean | string | OpenOptions;
62
/** Base URL path */
63
base?: string;
64
/** Static file serving */
65
publicDir?: PublicDir;
66
/** Custom middleware setup */
67
setupMiddlewares?: SetupMiddlewaresFn;
68
}
69
70
interface HTTPSOptions {
71
/** SSL private key */
72
key?: string;
73
/** SSL certificate */
74
cert?: string;
75
}
76
77
interface ProxyConfig {
78
[path: string]: string | ProxyOptions;
79
}
80
81
interface ProxyOptions {
82
/** Target server URL */
83
target: string;
84
/** Change origin header */
85
changeOrigin?: boolean;
86
/** Path rewriting rules */
87
pathRewrite?: Record<string, string>;
88
/** Request interceptor */
89
onProxyReq?: (proxyReq: any, req: any, res: any) => void;
90
/** Response interceptor */
91
onProxyRes?: (proxyRes: any, req: any, res: any) => void;
92
/** WebSocket proxying */
93
ws?: boolean;
94
/** Custom headers */
95
headers?: Record<string, string>;
96
}
97
98
interface HistoryApiFallbackOptions {
99
/** Rewrite rules */
100
rewrites?: Array<{ from: RegExp; to: string }>;
101
/** Files to serve directly */
102
disableDotRule?: boolean;
103
/** Verbose logging */
104
verbose?: boolean;
105
}
106
107
interface OpenOptions {
108
/** Target URL or app */
109
target?: string;
110
/** Browser app name */
111
app?: {
112
name: string;
113
arguments?: string[];
114
};
115
}
116
117
interface PublicDir {
118
/** Public directory path */
119
name?: string;
120
/** Copy to output directory */
121
copyOnBuild?: boolean;
122
}
123
124
type SetupMiddlewaresFn = (
125
middlewares: RequestHandler[],
126
server: SetupMiddlewaresContext
127
) => RequestHandler[] | void;
128
129
interface SetupMiddlewaresContext {
130
/** Express app instance */
131
app: any;
132
/** Development server instance */
133
server: RsbuildDevServer;
134
}
135
```
136
137
### Hot Module Replacement
138
139
```typescript { .api }
140
interface DevConfig {
141
/** Hot Module Replacement configuration */
142
hmr?: boolean | HMROptions;
143
/** Live reload on file changes */
144
liveReload?: boolean;
145
/** Development asset prefix */
146
assetPrefix?: string | 'auto';
147
/** Client-side development configuration */
148
client?: ClientConfig;
149
}
150
151
interface HMROptions {
152
/** HMR server port */
153
port?: number;
154
/** HMR server host */
155
host?: string;
156
/** HMR WebSocket path */
157
path?: string;
158
}
159
160
interface ClientConfig {
161
/** WebSocket protocol */
162
protocol?: 'ws' | 'wss';
163
/** Client connection port */
164
port?: number;
165
/** Client connection host */
166
host?: string;
167
/** WebSocket connection path */
168
path?: string;
169
/** Error overlay configuration */
170
overlay?: boolean | OverlayOptions;
171
}
172
173
interface OverlayOptions {
174
/** Show compilation errors */
175
errors?: boolean;
176
/** Show compilation warnings */
177
warnings?: boolean;
178
}
179
```
180
181
**Usage Examples:**
182
183
```typescript
184
import { createRsbuild, defineConfig } from "@rsbuild/core";
185
186
// Basic server configuration
187
const config = defineConfig({
188
server: {
189
port: 3000,
190
host: "localhost",
191
open: true,
192
},
193
dev: {
194
hmr: true,
195
liveReload: true,
196
},
197
});
198
199
// Advanced server configuration
200
const advancedConfig = defineConfig({
201
server: {
202
port: 8080,
203
host: "0.0.0.0",
204
https: {
205
key: "./ssl/private-key.pem",
206
cert: "./ssl/certificate.pem",
207
},
208
209
// Proxy API calls
210
proxy: {
211
"/api": {
212
target: "http://localhost:3001",
213
changeOrigin: true,
214
pathRewrite: {
215
"^/api": "/v1/api",
216
},
217
},
218
"/ws": {
219
target: "ws://localhost:3001",
220
ws: true,
221
},
222
},
223
224
// Custom headers
225
headers: {
226
"X-Custom-Header": "development",
227
},
228
229
// SPA routing
230
historyApiFallback: {
231
rewrites: [
232
{ from: /^\/admin/, to: "/admin.html" },
233
{ from: /./, to: "/index.html" },
234
],
235
},
236
237
// Custom middleware
238
setupMiddlewares: (middlewares, { app }) => {
239
// Add custom route
240
app.get("/api/health", (req, res) => {
241
res.json({ status: "ok" });
242
});
243
244
return middlewares;
245
},
246
},
247
248
dev: {
249
// Custom HMR configuration
250
hmr: {
251
port: 24678,
252
host: "localhost",
253
},
254
255
// Client configuration
256
client: {
257
overlay: {
258
errors: true,
259
warnings: false,
260
},
261
},
262
},
263
});
264
265
// Using the development server
266
const rsbuild = await createRsbuild({ rsbuildConfig: config });
267
268
// Start development server
269
const { urls, port, server } = await rsbuild.startDevServer();
270
console.log("Server running at:", urls);
271
272
// Or create server manually
273
const devServer = await rsbuild.createDevServer();
274
await devServer.listen();
275
console.log(`Server running on port ${devServer.port}`);
276
277
// Close server when needed
278
await devServer.close();
279
```
280
281
### Middleware System
282
283
```typescript { .api }
284
/**
285
* Request handler type for Express-like middleware
286
*/
287
type RequestHandler = (req: any, res: any, next?: () => void) => void;
288
289
/**
290
* Setup custom middleware function
291
*/
292
type SetupMiddlewaresFn = (
293
middlewares: RequestHandler[],
294
server: SetupMiddlewaresContext
295
) => RequestHandler[] | void;
296
```
297
298
**Middleware Examples:**
299
300
```typescript
301
const config = defineConfig({
302
server: {
303
setupMiddlewares: (middlewares, { app, server }) => {
304
// Add middleware before existing ones
305
middlewares.unshift((req, res, next) => {
306
console.log(`${req.method} ${req.url}`);
307
next();
308
});
309
310
// Add custom API endpoints
311
app.get("/api/config", (req, res) => {
312
res.json({
313
version: "1.0.0",
314
environment: "development",
315
});
316
});
317
318
// Add middleware after existing ones
319
middlewares.push((req, res, next) => {
320
res.setHeader("X-Powered-By", "Rsbuild");
321
next();
322
});
323
324
return middlewares;
325
},
326
},
327
});
328
```
329
330
### Client-Side Integration
331
332
Rsbuild provides client-side modules for HMR and error overlay functionality.
333
334
```typescript { .api }
335
// Available as separate exports
336
import "@rsbuild/core/client/hmr"; // HMR client
337
import "@rsbuild/core/client/overlay"; // Error overlay client
338
```
339
340
**Client Environment Variables:**
341
342
```typescript { .api }
343
// Available in client code during development
344
declare const import.meta.env: {
345
MODE: 'development' | 'production' | 'none';
346
DEV: boolean;
347
PROD: boolean;
348
BASE_URL: string;
349
ASSET_PREFIX: string;
350
};
351
```
352
353
### Development Hooks
354
355
Server-related lifecycle hooks for plugins and custom logic.
356
357
```typescript { .api }
358
/**
359
* Hook called before development server starts
360
*/
361
type OnBeforeStartDevServerFn = (params: {
362
port: number;
363
host: string;
364
}) => void | Promise<void>;
365
366
/**
367
* Hook called after development server starts
368
*/
369
type OnAfterStartDevServerFn = (params: {
370
port: number;
371
host: string;
372
urls: string[];
373
}) => void | Promise<void>;
374
375
/**
376
* Hook called when development server closes
377
*/
378
type OnCloseDevServerFn = () => void | Promise<void>;
379
```
380
381
**Hook Usage Examples:**
382
383
```typescript
384
const rsbuild = await createRsbuild({ rsbuildConfig: config });
385
386
// Before server starts
387
rsbuild.onBeforeStartDevServer(({ port, host }) => {
388
console.log(`Starting server on ${host}:${port}`);
389
});
390
391
// After server starts
392
rsbuild.onAfterStartDevServer(({ urls }) => {
393
console.log("Server started at:");
394
urls.forEach(url => console.log(` ${url}`));
395
});
396
397
// When server closes
398
rsbuild.onCloseDevServer(() => {
399
console.log("Development server closed");
400
});
401
402
await rsbuild.startDevServer();
403
```