0
# Core Middleware
1
2
The main webpack-dev-middleware function creates Express-style middleware that serves webpack bundles from memory during development.
3
4
## Primary Middleware Function
5
6
```javascript { .api }
7
function webpackDevMiddleware<RequestInternal, ResponseInternal>(
8
compiler: Compiler | MultiCompiler,
9
options?: Options<RequestInternal, ResponseInternal>
10
): API<RequestInternal, ResponseInternal>;
11
```
12
13
**Parameters:**
14
- `compiler`: Webpack `Compiler` or `MultiCompiler` instance
15
- `options`: Optional configuration object
16
17
**Returns:** Middleware function with additional API methods
18
19
## API Methods
20
21
The returned middleware includes additional methods for advanced control:
22
23
### getFilenameFromUrl
24
25
```javascript { .api }
26
getFilenameFromUrl(url: string, extra?: Extra): string | undefined;
27
```
28
29
Converts a URL to the corresponding filename in webpack's output file system.
30
31
**Parameters:**
32
- `url`: The URL to convert
33
- `extra`: Optional extra context including stats and error information
34
35
**Returns:** The filename or `undefined` if not found
36
37
**Example:**
38
```javascript
39
const middleware = webpackDevMiddleware(compiler);
40
const filename = middleware.getFilenameFromUrl("/bundle.js");
41
// Returns the actual file path in webpack's output
42
```
43
44
### waitUntilValid
45
46
```javascript { .api }
47
waitUntilValid(callback?: Callback): void;
48
```
49
50
Waits until webpack compilation is complete before executing the callback.
51
52
**Parameters:**
53
- `callback`: Optional callback function called when compilation is valid
54
55
**Example:**
56
```javascript
57
middleware.waitUntilValid((stats) => {
58
console.log("Webpack compilation is complete");
59
console.log("Stats:", stats);
60
});
61
```
62
63
### invalidate
64
65
```javascript { .api }
66
invalidate(callback?: Callback): void;
67
```
68
69
Invalidates the current webpack compilation and triggers recompilation, then waits for completion.
70
71
**Parameters:**
72
- `callback`: Optional callback function called when recompilation is complete
73
74
**Example:**
75
```javascript
76
// Force recompilation
77
middleware.invalidate((stats) => {
78
console.log("Recompilation complete");
79
});
80
```
81
82
### close
83
84
```javascript { .api }
85
close(callback?: (err: Error | null | undefined) => void): void;
86
```
87
88
Closes the middleware and stops webpack watching.
89
90
**Parameters:**
91
- `callback`: Optional callback function called when close operation completes
92
93
**Example:**
94
```javascript
95
// Shutdown the middleware
96
middleware.close((err) => {
97
if (err) console.error("Error closing middleware:", err);
98
else console.log("Middleware closed successfully");
99
});
100
```
101
102
### context
103
104
```javascript { .api }
105
context: Context<RequestInternal, ResponseInternal>;
106
```
107
108
Provides access to the internal middleware context and state.
109
110
## Context Interface
111
112
```javascript { .api }
113
interface Context<RequestInternal, ResponseInternal> {
114
state: boolean;
115
stats: Stats | MultiStats | undefined;
116
callbacks: Callback[];
117
options: Options<RequestInternal, ResponseInternal>;
118
compiler: Compiler | MultiCompiler;
119
watching: Watching | MultiWatching | undefined;
120
logger: Logger;
121
outputFileSystem: OutputFileSystem;
122
}
123
```
124
125
**Properties:**
126
- `state`: Current compilation state (true when valid)
127
- `stats`: Latest webpack compilation statistics
128
- `callbacks`: Pending callback functions
129
- `options`: Middleware configuration options
130
- `compiler`: The webpack compiler instance
131
- `watching`: Webpack file watching instance
132
- `logger`: Webpack infrastructure logger
133
- `outputFileSystem`: File system used for webpack output
134
135
## Type Definitions
136
137
```javascript { .api }
138
type Callback = (stats?: Stats | MultiStats) => void;
139
140
type NextFunction = (err?: any) => void;
141
142
interface Extra {
143
stats?: import("fs").Stats;
144
errorCode?: number;
145
immutable?: boolean;
146
}
147
148
type Logger = ReturnType<Compiler["getInfrastructureLogger"]>;
149
150
type OutputFileSystem = import("webpack").OutputFileSystem & {
151
createReadStream?: typeof import("fs").createReadStream;
152
statSync: import("fs").StatSyncFn;
153
readFileSync: typeof import("fs").readFileSync;
154
};
155
```
156
157
## Usage Examples
158
159
### Basic Express Integration
160
161
```javascript
162
const express = require("express");
163
const webpack = require("webpack");
164
const webpackDevMiddleware = require("webpack-dev-middleware");
165
166
const app = express();
167
const compiler = webpack(webpackConfig);
168
169
const middleware = webpackDevMiddleware(compiler, {
170
publicPath: "/assets/",
171
stats: "minimal"
172
});
173
174
app.use(middleware);
175
176
// Access additional functionality
177
middleware.waitUntilValid(() => {
178
console.log("Ready to serve requests");
179
});
180
```
181
182
### Programmatic File Access
183
184
```javascript
185
const middleware = webpackDevMiddleware(compiler);
186
187
app.get("/api/build-info", (req, res) => {
188
const stats = middleware.context.stats;
189
const isValid = middleware.context.state;
190
191
res.json({
192
buildComplete: isValid,
193
compilation: stats ? stats.toJson() : null
194
});
195
});
196
```
197
198
### Manual Invalidation
199
200
```javascript
201
const middleware = webpackDevMiddleware(compiler);
202
203
// Trigger rebuild when files change outside webpack's watch
204
app.post("/api/rebuild", (req, res) => {
205
middleware.invalidate((stats) => {
206
res.json({ success: true, stats: stats.toJson() });
207
});
208
});
209
```