Uh oh!
There was an error while loading.Please reload this page.
- Notifications
You must be signed in to change notification settings - Fork381
A development middleware for webpack
License
webpack/webpack-dev-middleware
Folders and files
Name | Name | Last commit message | Last commit date | |
---|---|---|---|---|
Repository files navigation
An express-style development middleware for use withwebpackbundles and allows for serving of the files emitted from webpack.This should be used fordevelopment 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 compilinghas 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.
constexpress=require("express");constwebpack=require("webpack");constmiddleware=require("webpack-dev-middleware");constcompiler=webpack({// webpack options});constapp=express();app.use(middleware(compiler,{// webpack-dev-middleware options}),);app.listen(3000,()=>console.log("Example app listening on port 3000!"));
Seebelow 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 | Iffalse (but notundefined ), 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. |
etag | boolean| "weak"| "strong" | undefined | Enable or disable etag generation. |
lastModified | boolean | undefined | Enable or disableLast-Modified header. Uses the file system's last modified value. |
cacheControl | boolean|number|string|Object | undefined | Enable or disable settingCache-Control response header. |
cacheImmutable | boolean\ | undefined | Enable or disable settingCache-Control: public, max-age=31536000, immutable response header for immutable assets. |
publicPath | string | undefined | 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 yourwebpack 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 anoptions
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:()=>({"Last-Modified":newDate(),}),});
or
webpackDevMiddleware(compiler,{headers:(req,res,context)=>{res.setHeader("Last-Modified",newDate());},});
or
webpackDevMiddleware(compiler,{headers:[{key:"X-custom-header",value:"foo",},{key:"Y-custom-header",value:"bar",},],});
or
webpackDevMiddleware(compiler,{headers:()=>[{key:"X-custom-header",value:"foo",},{key:"Y-custom-header",value:"bar",},],});
Type:Boolean|String
Default:index.html
Iffalse
(but notundefined
), the server will not respond to requests to the root URL.
Type:Object
Default:undefined
This property allows a user to register custom mime types or extension mappings.eg.mimeTypes: { phtml: 'text/html' }
.
Please see the documentation formime-types
for more information.
Type:String
Default:undefined
This property allows a user to register a default mime type when we can't determine the content type.
Type:"weak" | "strong"
Default:undefined
Enable or disable etag generation. Boolean value use
Type:Boolean
Default:undefined
Enable or disableLast-Modified
header. Uses the file system's last modified value.
Type:Boolean | Number | String | { maxAge?: number, immutable?: boolean }
Default:undefined
Depending on the setting, the following headers will be generated:
Boolean
-Cache-Control: public, max-age=31536000000
Number
-Cache-Control: public, max-age=YOUR_NUMBER
String
-Cache-Control: YOUR_STRING
{ maxAge?: number, immutable?: boolean }
-Cache-Control: public, max-age=YOUR_MAX_AGE_or_31536000000
, also, immutable
can be added if you set theimmutable
option totrue
Enable or disable settingCache-Control
response header.
Type:Boolean
Default:undefined
Enable or disable settingCache-Control: public, max-age=31536000, immutable
response header for immutable assets (i.e. asset with a hash likeimage.a4c12bde.jpg
).Immutable assets are assets that have their hash in the file name therefore they can be cached, because if you change their contents the file name will be changed.Take preference over thecacheControl
option if the asset was defined as immutable.
Type:String
Default:output.publicPath
(from a configuration)
The public path that the middleware is bound to.
Best Practice: use the samepublicPath
defined in your webpack config. For more information aboutpublicPath
, please seethe webpack documentation.
Type:Boolean|String|Object
Default:stats
(from a configuration)
Stats options object or preset name.
Type:Boolean
Default:undefined
Instructs the module to enable or disable the server-side rendering mode.Please seeServer-Side Rendering for more information.
Type:Boolean|Function
Default:false
Iftrue
, the option will instruct the module to write files to the configured location on disk as specified in yourwebpack
config file.SettingwriteToDisk: true
won't change the behavior of thewebpack-dev-middleware
, and bundle files accessed through the browser will still be served from memory.This option provides the same capabilities as theWriteFilePlugin
.
This option also accepts aFunction
value, which can be used to filter which files are written to disk.The function follows the same premise asArray#filter
in which a return value offalse
will not write the file, and a return value oftrue
will write the file to disk. eg.
constwebpack=require("webpack");constconfiguration={/* Webpack configuration */};constcompiler=webpack(configuration);middleware(compiler,{writeToDisk:(filePath)=>/superman\.css$/.test(filePath),});
Type:Object
Default:memfs
Set the default file system which will be used by webpack as primary destination of generated files.This option isn't affected by thewriteToDisk option.
You have to provide.join()
andmkdirp
method to theoutputFileSystem
instance manually for compatibility withwebpack@4
.
This can be done simply by usingpath.join
:
constpath=require("node:path");constmkdirp=require("mkdirp");constmyOutputFileSystem=require("my-fs");constwebpack=require("webpack");myOutputFileSystem.join=path.join.bind(path);// no need to bindmyOutputFileSystem.mkdirp=mkdirp.bind(mkdirp);// no need to bindconstcompiler=webpack({/* Webpack configuration */});middleware(compiler,{outputFileSystem:myOutputFileSystem});
Allows to set up a callback to change the response data.
constwebpack=require("webpack");constconfiguration={/* Webpack configuration */};constcompiler=webpack(configuration);middleware(compiler,{// Note - if you send the `Range` header you will have `ReadStream`// Also `data` can be `string` or `Buffer`modifyResponseData:(req,res,data,byteLength)=>// Your logic// Don't use `res.end()` or `res.send()` here({ data, byteLength}),});
webpack-dev-middleware
also provides convenience methods that can be use tointeract with the middleware at runtime:
Instructswebpack-dev-middleware
instance to stop watching for file changes.
Type:Function
Required:No
A function executed once the middleware has stopped watching.
constexpress=require("express");constwebpack=require("webpack");constcompiler=webpack({/* Webpack configuration */});constmiddleware=require("webpack-dev-middleware");constinstance=middleware(compiler);// eslint-disable-next-line new-capconstapp=newexpress();app.use(instance);setTimeout(()=>{// Says `webpack` to stop watch changesinstance.close();},1000);
Instructswebpack-dev-middleware
instance to recompile the bundle, e.g. after a change to the configuration.
Type:Function
Required:No
A function executed once the middleware has invalidated.
constexpress=require("express");constwebpack=require("webpack");constcompiler=webpack({/* Webpack configuration */});constmiddleware=require("webpack-dev-middleware");constinstance=middleware(compiler);// eslint-disable-next-line new-capconstapp=newexpress();app.use(instance);setTimeout(()=>{// After a short delay the configuration is changed and a banner plugin is added to the confignewwebpack.BannerPlugin("A new banner").apply(compiler);// Recompile the bundle with the banner plugin:instance.invalidate();},1000);
Executes a callback function when the compiler bundle is valid, typically aftercompilation.
Type:Function
Required:No
A function executed when the bundle becomes valid.If the bundle is valid at the time of calling, the callback is executed immediately.
constexpress=require("express");constwebpack=require("webpack");constcompiler=webpack({/* Webpack configuration */});constmiddleware=require("webpack-dev-middleware");constinstance=middleware(compiler);// eslint-disable-next-line new-capconstapp=newexpress();app.use(instance);instance.waitUntilValid(()=>{console.log("Package is in a valid state");});
Get filename from URL.
Type:String
Required:Yes
URL for the requested file.
constexpress=require("express");constwebpack=require("webpack");constcompiler=webpack({/* Webpack configuration */});constmiddleware=require("webpack-dev-middleware");constinstance=middleware(compiler);// eslint-disable-next-line new-capconstapp=newexpress();app.use(instance);instance.waitUntilValid(()=>{constfilename=instance.getFilenameFromUrl("/bundle.js");console.log(`Filename is${filename}`);});
Sinceoutput.publicPath
andoutput.filename
/output.chunkFilename
can be dynamic, it's not possible to know which files are webpack bundles (and they public paths) and which are not, so we can't avoid blocking requests.
But there is a solution to avoid it - mount the middleware to a non-root route, for example:
constexpress=require("express");constwebpack=require("webpack");constmiddleware=require("webpack-dev-middleware");constcompiler=webpack({// webpack options});constapp=express();// Mounting the middleware to the non-root route allows avoids this.// Note - check your public path, if you want to handle `/dist/`, you need to setup `output.publicPath` to `/` value.app.use("/dist/",middleware(compiler,{// webpack-dev-middleware options}),);app.listen(3000,()=>console.log("Example app listening on port 3000!"));
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 thestats
, which isgenerated with each build.
With server-side rendering enabled,webpack-dev-middleware
sets thestats
tores.locals.webpack.devMiddleware.stats
and the filesystem tores.locals.webpack.devMiddleware.outputFileSystem
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 bywebpack-dev-middleware
and all requests will be pending until the buildprocess is finished with server-side rendering enabled.
Example Implementation:
constexpress=require("express");constisObject=require("is-object");constwebpack=require("webpack");constmiddleware=require("webpack-dev-middleware");constcompiler=webpack({/* Webpack configuration */});// eslint-disable-next-line new-capconstapp=newexpress();// This function makes server rendering of asset references consistent with different webpack chunk/entry configurationsfunctionnormalizeAssets(assets){if(isObject(assets)){returnObject.values(assets);}returnArray.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{ devMiddleware}=res.locals.webpack;const{ outputFileSystem}=devMiddleware;constjsonWebpackStats=devMiddleware.stats.toJson();const{ assetsByChunkName, outputPath}=jsonWebpackStats;// Then use `assetsByChunkName` for server-side rendering// For example, if you have only one main chunk:res.send(`<html> <head> <title>My App</title> <style>${normalizeAssets(assetsByChunkName.main).filter((path)=>path.endsWith(".css")).map((path)=>outputFileSystem.readFileSync(path.join(outputPath,path))).join("\n")} </style> </head> <body> <div></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, andneeded modifications to the code for the module. Because of that, we ask userswith general support, "how-to", or "why isn't this working" questions to try oneof the other support channels that are available.
Your first-stop-shop for support for webpack-dev-server should by the excellentdocumentation for the module. If you see an opportunity for improvementof those docs, please head over to thewebpack.js.org repo and open apull request.
From there, we encourage users to visit thewebpack discussions andtalk to the fine folks there. If your quest for answers comes up dry in chat,head over toStackOverflow and do a quick search or open a newquestion. Remember; It's always much easier to answer questions that include yourwebpack.config.js
and relevant files!
If you're twitter-savvy you can tweet#webpack with your questionand someone should be able to reach out and lend a hand.
If you have discovered a 🐛, have a feature suggestion, or would like to seea modification, please feel free to create an issue on Github.Note: The issuetemplate isn't optional, so please be sure not to remove it, and please fill itout completely.
Examples of use with other servers will follow here.
consthttp=require("node:http");constconnect=require("connect");constwebpack=require("webpack");constdevMiddleware=require("webpack-dev-middleware");constwebpackConfig=require("./webpack.config.js");constcompiler=webpack(webpackConfig);constdevMiddlewareOptions={/** Your webpack-dev-middleware-options */};constapp=connect();app.use(devMiddleware(compiler,devMiddlewareOptions));http.createServer(app).listen(3000);
consthttp=require("node:http");constfinalhandler=require("finalhandler");constRouter=require("router");constwebpack=require("webpack");constdevMiddleware=require("webpack-dev-middleware");constwebpackConfig=require("./webpack.config.js");constcompiler=webpack(webpackConfig);constdevMiddlewareOptions={/** Your webpack-dev-middleware-options */};// eslint-disable-next-line new-capconstrouter=Router();router.use(devMiddleware(compiler,devMiddlewareOptions));constserver=http.createServer((req,res)=>{router(req,res,finalhandler(req,res));});server.listen(3000);
constexpress=require("express");constwebpack=require("webpack");constdevMiddleware=require("webpack-dev-middleware");constwebpackConfig=require("./webpack.config.js");constcompiler=webpack(webpackConfig);constdevMiddlewareOptions={/** Your webpack-dev-middleware-options */};constapp=express();app.use(devMiddleware(compiler,devMiddlewareOptions));app.listen(3000,()=>console.log("Example app listening on port 3000!"));
constKoa=require("koa");constwebpack=require("webpack");constmiddleware=require("webpack-dev-middleware");constwebpackConfig=require("./webpack.simple.config");constcompiler=webpack(webpackConfig);constdevMiddlewareOptions={/** Your webpack-dev-middleware-options */};constapp=newKoa();app.use(middleware.koaWrapper(compiler,devMiddlewareOptions));app.listen(3000);
constHapi=require("@hapi/hapi");constwebpack=require("webpack");constdevMiddleware=require("webpack-dev-middleware");constwebpackConfig=require("./webpack.config.js");constcompiler=webpack(webpackConfig);constdevMiddlewareOptions={};constserver=Hapi.server({port:3000,host:"localhost"});awaitserver.register({plugin:devMiddleware.hapiPlugin(),options:{// The `compiler` option is required compiler, ...devMiddlewareOptions,},});awaitserver.start();console.log("Server running on %s",server.info.uri);process.on("unhandledRejection",(err)=>{console.log(err);process.exit(1);});
Fastify interop will require the use offastify-express
instead ofmiddie
for providing middleware support. As the authors offastify-express
recommend, this should only be used as a stopgap while full Fastify support is worked on.
constfastify=require("fastify")();constwebpack=require("webpack");constdevMiddleware=require("webpack-dev-middleware");constwebpackConfig=require("./webpack.config.js");constcompiler=webpack(webpackConfig);constdevMiddlewareOptions={/** Your webpack-dev-middleware-options */};awaitfastify.register(require("@fastify/express"));awaitfastify.use(devMiddleware(compiler,devMiddlewareOptions));awaitfastify.listen(3000);
import{serve}from"@hono/node-server";import{Hono}from"hono";importwebpackfrom"webpack";importdevMiddlewarefrom"webpack-dev-middleware";importwebpackConfigfrom"./webpack.config.js";constcompiler=webpack(webpackConfig);constdevMiddlewareOptions={/** Your webpack-dev-middleware-options */};constapp=newHono();app.use(devMiddleware.honoWrapper(compiler,devMiddlewareOptions));serve(app);
Please take a moment to read our contributing guidelines if you haven't yet done so.
About
A development middleware for webpack
Topics
Resources
License
Code of conduct
Security policy
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Sponsor this project
Uh oh!
There was an error while loading.Please reload this page.