What is webpack-dev-middleware?
webpack-dev-middleware is a package that provides a simple way to serve and live reload webpack bundles for development purposes. It's designed to be used with a Node.js server, such as Express, and it allows developers to serve the webpack-generated files without writing them to disk, providing a faster development experience.
What are webpack-dev-middleware's main functionalities?
Serving Webpack Bundles
This code sample demonstrates how to set up webpack-dev-middleware with an Express server. It serves the files generated by webpack based on the provided configuration.
const express = require('express');
const webpack = require('webpack');
const webpackDevMiddleware = require('webpack-dev-middleware');
const config = require('./webpack.config.js');
const compiler = webpack(config);
const app = express();
app.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath
}));
app.listen(3000, function () {
console.log('Example app listening on port 3000!\n');
});
Enabling Hot Module Replacement (HMR)
This code sample shows how to enable Hot Module Replacement (HMR) in conjunction with webpack-dev-middleware. It requires an additional package, webpack-hot-middleware, to work.
const webpackHotMiddleware = require('webpack-hot-middleware');
app.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath
}));
app.use(webpackHotMiddleware(compiler));
Other packages similar to webpack-dev-middleware
browser-sync
BrowserSync is a package that allows for live reloading of web pages as files are edited and saved. It can be integrated with webpack using browser-sync-webpack-plugin. Unlike webpack-dev-middleware, BrowserSync is focused on synchronizing interactions across multiple devices/browsers during testing.
serve
Serve is a static file serving and directory listing package that can be used for quick prototyping and local development. It does not have built-in webpack integration or HMR, but it's a simple alternative for serving static files.
webpack-hot-server-middleware
webpack-hot-server-middleware is similar to webpack-dev-middleware but is specifically designed for use with server-side rendering in Node.js applications. It works in tandem with webpack-dev-middleware and webpack-hot-middleware to enable HMR for server-rendered apps.
webpack-serve
webpack-serve is a now-deprecated package that was once an alternative to webpack-dev-middleware. It provided a development server that used webpack's watch mode to observe file changes and recompile automatically. It has since been replaced by webpack-dev-server, which offers similar functionality.
webpack Dev Middleware
It's a simple wrapper middleware for webpack. It serves the files emitted from webpack over a connect server. This should be used for development only.
It has a few advantages over bundling it as files:
- No files are written to disk, it handle the files in memory
- If files changed in watch mode, the middleware no longer serves the old bundle, but delays requests until the compiling has finished. You don't have to wait before refreshing the page after a file modification.
- I may add some specific optimization in future releases.
Install
npm install webpack-dev-middleware --save-dev
Usage
var webpackMiddleware = require("webpack-dev-middleware");
app.use(webpackMiddleware(...));
Example usage:
app.use(webpackMiddleware(webpack({
entry: "...",
output: {
path: "/"
}
}), {
noInfo: false,
quiet: false,
lazy: true,
watchOptions: {
aggregateTimeout: 300,
poll: true
},
publicPath: "/assets/",
index: "index.html",
headers: { "X-Custom-Header": "yes" },
mimeTypes: { "text/html": [ "phtml" ] },
stats: {
colors: true
},
reporter: null,
serverSideRender: false,
}));
Advanced API
This part shows how you might interact with the middleware during runtime:
-
close(callback)
- stop watching for file changes
var webpackDevMiddlewareInstance = webpackMiddleware();
app.use(webpackDevMiddlewareInstance);
setTimeout(function(){
webpackDevMiddlewareInstance.close();
}, 10000);
-
invalidate()
- recompile the bundle - e.g. after you changed the configuration
var compiler = webpack();
var webpackDevMiddlewareInstance = webpackMiddleware(compiler);
app.use(webpackDevMiddlewareInstance);
setTimeout(function(){
compiler.apply(new webpack.BannerPlugin('A new banner'));
webpackDevMiddlewareInstance.invalidate();
}, 1000);
-
waitUntilValid(callback)
- executes the callback
if the bundle is valid or after it is valid again:
var webpackDevMiddlewareInstance = webpackMiddleware();
app.use(webpackDevMiddlewareInstance);
webpackDevMiddlewareInstance.waitUntilValid(function(){
console.log('Package is in a valid state');
});
Server-Side Rendering
Note: this feature is experimental and may be removed or changed completely in the future.
In order to develop a server-side rendering application, we need access to the stats
, which is generated with the latest build.
In the server-side rendering mode, webpack-dev-middleware sets the stat
to res.locals.webpackStats
before invoking the next middleware, allowing a developer to render the page body and manage the response to clients.
Notice that requests for bundle files would still be responded by webpack-dev-middleware and all requests will be pending until the building process is finished in the server-side rendering mode.
function normalizeAssets(assets) {
return Array.isArray(assets) ? assets : [assets]
}
app.use(webpackMiddleware(compiler, { serverSideRender: true })
app.use((req, res) => {
const assetsByChunkName = res.locals.webpackStats.toJson().assetsByChunkName
res.send(`
<html>
<head>
<title>My App</title>
${
normalizeAssets(assetsByChunkName.main)
.filter(path => path.endsWith('.css'))
.map(path => `<link rel="stylesheet" href="${path}" />`)
.join('\n')
}
</head>
<body>
<div id="root"></div>
${
normalizeAssets(assetsByChunkName.main)
.filter(path => path.endsWith('.js'))
.map(path => `<script src="${path}"></script>`)
.join('\n')
}
</body>
</html>
`)
})
Contributing
Don't hesitate to create a pull request. Every contribution is appreciated. In development you can start the tests by calling npm test
.
Maintainers
LICENSE