An express-style development middleware for use with webpack bundles and allows for serving of the files emitted from webpack. This should be used for development only.
Some of the benefits of using this middleware include:
- No files are written to disk, rather it handles files in memory
- If files changed in watch mode, the middleware delays requests until compiling has completed.
- Supports hot module reload (HMR).
First thing's first, install the module:
npm install webpack-dev-middleware --save-dev
Warning
We do not recommend installing this module globally.
const webpack = require("webpack");
const middleware = require("webpack-dev-middleware");
const compiler = webpack({
// webpack options
});
const express = require("express");
const app = express();
app.use(
middleware(compiler, {
// webpack-dev-middleware options
}),
);
app.listen(3000, () => console.log("Example app listening on port 3000!"));
See below for an example of use with fastify.
Name | Type | Default | Description |
---|---|---|---|
methods |
Array |
[ 'GET', 'HEAD' ] |
Allows to pass the list of HTTP request methods accepted by the middleware |
headers |
Array|Object|Function |
undefined |
Allows to pass custom HTTP headers on each request. |
index |
Boolean|String |
index.html |
If false (but not undefined ), the server will not respond to requests to the root URL. |
mimeTypes |
Object |
undefined |
Allows to register custom mime types or extension mappings. |
mimeTypeDefault |
String |
undefined |
Allows to register a default mime type when we can't determine the content type. |
publicPath |
String |
output.publicPath (from a configuration) |
The public path that the middleware is bound to. |
stats |
Boolean|String|Object |
stats (from a configuration) |
Stats options object or preset name. |
serverSideRender |
Boolean |
undefined |
Instructs the module to enable or disable the server-side rendering mode. |
writeToDisk |
Boolean|Function |
false |
Instructs the module to write files to the configured location on disk as specified in your webpack configuration. |
outputFileSystem |
Object |
memfs |
Set the default file system which will be used by webpack as primary destination of generated files. |
modifyResponseData |
Function |
undefined |
Allows to set up a callback to change the response data. |
The middleware accepts an options
Object. The following is a property reference for the Object.
Type: Array
Default: [ 'GET', 'HEAD' ]
This property allows a user to pass the list of HTTP request methods accepted by the middleware**.
Type: Array|Object|Function
Default: undefined
This property allows a user to pass custom HTTP headers on each request.
eg. { "X-Custom-Header": "yes" }
or
webpackDevMiddleware(compiler, {
headers: () => {
return {
"Last-Modified": new Date(),
};
},
});
or
webpackDevMiddleware(compiler, {
headers: (req, res, context) => {
res.setHeader("Last-Modified", new Date());
},
});