![New axobject-query Maintainer Faces Backlash Over Controversial Decision to Support Legacy Node.js Versions](https://cdn.sanity.io/images/cgdhsj6q/production/86e6ebdea652d20da070ebbda20134b839972db7-1024x1024.webp?w=800&fit=max&auto=format)
Security News
New axobject-query Maintainer Faces Backlash Over Controversial Decision to Support Legacy Node.js Versions
A JavaScript library maintainer is under fire after merging a controversial PR to support legacy versions of Node.js.
webpack-dev-middleware
Advanced tools
Package description
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.
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));
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 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 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 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.
Readme
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:
First thing's first, install the module:
npm install webpack-dev-middleware --save-dev
Note: We do not recommend installing this module globally.
webpack-dev-middleware
requires Node v6 or higher, and must be used with a
server that accepts express-style middleware.
const webpack = require('webpack');
const middlware = 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!'))
The middleware accepts an options
Object. The following is a property reference
for the Object.
Note: The publicPath
property is required, whereas all other options are optional
Type: Object
Default: undefined
This property allows a user to pass custom HTTP headers on each request. eg.
{ "X-Custom-Header": "yes" }
index
Type: String
Default: undefined
"index.html", // The index path for web server, defaults to "index.html". // If falsy (but not undefined), the server will not respond to requests to the root URL.
Type: Boolean
Default: undefined
This option instructs the module to operate in 'lazy' mode, meaning that it won't recompile when files change, but rather on each request.
Type: Object
Default: log
In the rare event that a user would like to provide a custom logging interface,
this property allows the user to assign one. The module leverages
loglevel
for logging management by default, and any custom logger must adhere to the same
exports for compatibility. Specifically, all custom loggers must have the
following exported methods at a minimum:
log.trace
log.debug
log.info
log.warn
log.error
Please see the documentation for loglevel
for more information.
Type: String
Default: 'info'
This property defines the level of messages that the module will log. Valid levels include:
trace
debug
info
warn
error
silent
Setting a log level means that all other levels below it will be visible in the
console. Setting logLevel: 'silent'
will hide all console output. The module
leverages loglevel
for logging management, and more information can be found on its page.
Type: Boolean
Default: false
If true
the log output of the module will be prefixed by a timestamp in the
HH:mm:ss
format.
Type: Object
Default: null
This property allows a user to register custom mime types or extension mappings.
eg. { 'text/html': [ 'phtml' ] }
. Please see the documentation for
node-mime
for more information.
Type: String
Required
The public path that the middleware is bound to. Best Prectice: use the same
publicPath
defined in your webpack config.
Type: Object
Default: undefined
Allows users to provide a custom reporter to handle logging within the module. Please see the default reporter for an example.
Type: Boolean
Default: undefined
Instructs the module to enable or disable the server-side rendering mode. Please see Server-Side Rendering for more information.
Type: Object
Default: { context: process.cwd() }
Options for formatting statistics displayed during and after compile. For more information and property details, please see the webpack documentation.
Type: Object
Default: `{ aggregateTimeout: 200 }``
The module accepts an Object
containing options for file watching, which is
passed directly to the compiler provided. For more information on watch options
please see the webpack documentation
webpack-dev-middleware
also provides convenience methods that can be use to
interact with the middleware at runtime:
close(callback)
Instructs a webpack-dev-middleware instance to stop watching for file changes.
Type: Function
A function executed once the middleware has stopped watching.
invalidate()
Instructs a webpack-dev-middleware instance to recompile the bundle. e.g. after a change to the configuration.
const webpack = require('webpack');
const compiler = webpack({ ... });
const middlware = require('webpack-dev-middleware');
const instance = middleware(compiler);
app.use(instance);
setTimeout(() => {
// After a short delay the configuration is changed and a banner plugin is added
// to the config
compiler.apply(new webpack.BannerPlugin('A new banner'));
// Recompile the bundle with the banner plugin:
instance.invalidate();
}, 1000);
waitUntilValid(callback)
Executes a callback function when the compiler bundle is valid, typically after compilation.
Type: Function
A function executed when the bundle becomes valid. If the bundle is valid at the time of calling, the callback is executed immediately.
const webpack = require('webpack');
const compiler = webpack({ ... });
const middlware = require('webpack-dev-middleware');
const instance = middleware(compiler);
app.use(instance);
instance.waitUntilValid(() => {
console.log('Package is in a valid state');
});
Note: this feature is experimental and may be removed or changed completely in the future.
In order to develop an app using server-side rendering, we need access to the
stats
, which is
generated with each build.
With server-side rendering enabled, 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.
Note: Requests for bundle files will still be handled by
webpack-dev-middleware
and all requests will be pending until the build
process is finished with server-side rendering enabled.
Example Implementation:
const webpack = require('webpack');
const compiler = webpack({ ... });
const middlware = require('webpack-dev-middleware');
// This function makes server rendering of asset references consistent with different webpack chunk/entry configurations
function normalizeAssets(assets) {
return Array.isArray(assets) ? assets : [assets]
}
app.use(middleware(compiler, { serverSideRender: true })
// The following middleware would not be invoked until the latest build is finished.
app.use((req, res) => {
const assetsByChunkName = res.locals.webpackStats.toJson().assetsByChunkName
// then use `assetsByChunkName` for server-sider rendering
// For example, if you have only one main chunk:
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>
`)
})
We do our best to keep Issues in the repository focused on bugs, features, and needed modifications to the code for the module. Because of that, we ask users with general support, "how-to", or "why isn't this working" questions to try one of the other support channels that are available.
Your first-stop-shop for support for webpack-dev-server should by the excellent documentation for the module. If you see an opportunity for improvement of those docs, please head over to the webpack.js.org repo and open a pull request.
From there, we encourage users to visit the webpack Gitter chat and
talk to the fine folks there. If your quest for answers comes up dry in chat,
head over to StackOverflow and do a quick search or open a new
question. Remember; It's always much easier to answer questions that include your
webpack.config.js
and relevant files!
If you're twitter-savvy you can tweet #webpack with your question and someone should be able to reach out and lend a hand.
If you have discovered a :bug:, have a feature suggestion, of would like to see a modification, please feel free to create an issue on Github. Note: The issue template isn't optional, so please be sure not to remove it, and please fill it out completely.
We welcome your contributions! Please have a read of CONTRIBUTING.md for more information on how to get involved.
Kees Kluskens |
![]() Andrew Powell |
FAQs
A development middleware for webpack
The npm package webpack-dev-middleware receives a total of 14,694,125 weekly downloads. As such, webpack-dev-middleware popularity was classified as popular.
We found that webpack-dev-middleware demonstrated a healthy version release cadence and project activity because the last version was released less than a year ago. It has 4 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Security News
A JavaScript library maintainer is under fire after merging a controversial PR to support legacy versions of Node.js.
Security News
Results from the 2023 State of JavaScript Survey highlight key trends, including Vite's dominance, rising TypeScript adoption, and the enduring popularity of React. Discover more insights on developer preferences and technology usage.
Security News
The US Justice Department has penalized two consulting firms $11.3 million for failing to meet cybersecurity requirements on federally funded projects, emphasizing strict enforcement to protect sensitive government data.