{"id":13396666,"url":"https://github.com/webpack/webpack-dev-middleware","last_synced_at":"2025-05-12T05:29:09.982Z","repository":{"id":4224803,"uuid":"5347074","full_name":"webpack/webpack-dev-middleware","owner":"webpack","description":"A development middleware for webpack","archived":false,"fork":false,"pushed_at":"2025-05-08T11:13:30.000Z","size":13243,"stargazers_count":2509,"open_issues_count":11,"forks_count":380,"subscribers_count":33,"default_branch":"master","last_synced_at":"2025-05-08T17:58:02.620Z","etag":null,"topics":["middleware","webpack","webpack-dev-middleware"],"latest_commit_sha":null,"homepage":"","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/webpack.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":"CONTRIBUTING.md","funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":".github/CODEOWNERS","security":"SECURITY.md","support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null},"funding":{"open_collective":"webpack"}},"created_at":"2012-08-08T20:20:33.000Z","updated_at":"2025-05-07T13:59:55.000Z","dependencies_parsed_at":"2024-03-04T11:05:35.013Z","dependency_job_id":"0af115e5-783e-4548-939f-616c5d40d530","html_url":"https://github.com/webpack/webpack-dev-middleware","commit_stats":{"total_commits":1522,"total_committers":116,"mean_commits":"13.120689655172415","dds":0.5315374507227333,"last_synced_commit":"6cbadcff8199177e12ff73dfbf81f253f31ffac7"},"previous_names":[],"tags_count":86,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webpack%2Fwebpack-dev-middleware","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webpack%2Fwebpack-dev-middleware/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webpack%2Fwebpack-dev-middleware/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/webpack%2Fwebpack-dev-middleware/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/webpack","download_url":"https://codeload.github.com/webpack/webpack-dev-middleware/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253124211,"owners_count":21857612,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["middleware","webpack","webpack-dev-middleware"],"created_at":"2024-07-30T18:00:59.435Z","updated_at":"2025-05-08T17:58:13.426Z","avatar_url":"https://github.com/webpack.png","language":"JavaScript","readme":"\u003cdiv align=\"center\"\u003e\n  \u003ca href=\"https://github.com/webpack/webpack\"\u003e\n    \u003cimg width=\"200\" height=\"200\" src=\"https://webpack.js.org/assets/icon-square-big.svg\"\u003e\n  \u003c/a\u003e\n\u003c/div\u003e\n\n[![npm][npm]][npm-url]\n[![node][node]][node-url]\n[![tests][tests]][tests-url]\n[![coverage][cover]][cover-url]\n[![discussion][discussion]][discussion-url]\n[![size][size]][size-url]\n\n# webpack-dev-middleware\n\nAn express-style development middleware for use with [webpack](https://webpack.js.org)\nbundles and allows for serving of the files emitted from webpack.\nThis should be used for **development only**.\n\nSome of the benefits of using this middleware include:\n\n- No files are written to disk, rather it handles files in memory\n- If files changed in watch mode, the middleware delays requests until compiling\n  has completed.\n- Supports hot module reload (HMR).\n\n## Getting Started\n\nFirst thing's first, install the module:\n\n```console\nnpm install webpack-dev-middleware --save-dev\n```\n\n\u003e [!WARNING]\n\u003e\n\u003e _We do not recommend installing this module globally._\n\n## Usage\n\n```js\nconst webpack = require(\"webpack\");\nconst middleware = require(\"webpack-dev-middleware\");\nconst compiler = webpack({\n  // webpack options\n});\nconst express = require(\"express\");\nconst app = express();\n\napp.use(\n  middleware(compiler, {\n    // webpack-dev-middleware options\n  }),\n);\n\napp.listen(3000, () =\u003e console.log(\"Example app listening on port 3000!\"));\n```\n\nSee [below](#other-servers) for an example of use with fastify.\n\n## Options\n\n|                      Name                       |               Type                |                    Default                    | Description                                                                                                          |\n| :---------------------------------------------: | :-------------------------------: | :-------------------------------------------: | :------------------------------------------------------------------------------------------------------------------- |\n|            **[`methods`](#methods)**            |              `Array`              |              `[ 'GET', 'HEAD' ]`              | Allows to pass the list of HTTP request methods accepted by the middleware                                           |\n|            **[`headers`](#headers)**            |     `Array\\|Object\\|Function`     |                  `undefined`                  | Allows to pass custom HTTP headers on each request.                                                                  |\n|              **[`index`](#index)**              |         `boolean\\|string`         |                 `index.html`                  | If `false` (but not `undefined`), the server will not respond to requests to the root URL.                           |\n|          **[`mimeTypes`](#mimetypes)**          |             `Object`              |                  `undefined`                  | Allows to register custom mime types or extension mappings.                                                          |\n|    **[`mimeTypeDefault`](#mimetypedefault)**    |             `string`              |                  `undefined`                  | Allows to register a default mime type when we can't determine the content type.                                     |\n|               **[`etag`](#tag)**                |   `boolean\\| \"weak\"\\| \"strong\"`   |                  `undefined`                  | Enable or disable etag generation.                                                                                   |\n|       **[`lastModified`](#lastmodified)**       |             `boolean`             |                  `undefined`                  | Enable or disable `Last-Modified` header. Uses the file system's last modified value.                                |\n|       **[`cacheControl`](#cachecontrol)**       | `boolean\\|number\\|string\\|Object` |                  `undefined`                  | Enable or disable setting `Cache-Control` response header.                                                           |\n|     **[`cacheImmutable`](#cacheimmutable)**     |            `boolean\\`             |                  `undefined`                  | Enable or disable setting `Cache-Control: public, max-age=31536000, immutable` response header for immutable assets. |\n|         **[`publicPath`](#publicpath)**         |             `string`              |                  `undefined`                  | The public path that the middleware is bound to.                                                                     |\n|              **[`stats`](#stats)**              |     `boolean\\|string\\|Object`     |        `stats` (from a configuration)         | Stats options object or preset name.                                                                                 |\n|   **[`serverSideRender`](#serversiderender)**   |             `boolean`             |                  `undefined`                  | Instructs the module to enable or disable the server-side rendering mode.                                            |\n|        **[`writeToDisk`](#writetodisk)**        |        `boolean\\|Function`        |                    `false`                    | Instructs the module to write files to the configured location on disk as specified in your `webpack` configuration. |\n|   **[`outputFileSystem`](#outputfilesystem)**   |             `Object`              | [`memfs`](https://github.com/streamich/memfs) | Set the default file system which will be used by webpack as primary destination of generated files.                 |\n| **[`modifyResponseData`](#modifyresponsedata)** |            `Function`             |                  `undefined`                  | Allows to set up a callback to change the response data.                                                             |\n\nThe middleware accepts an `options` Object. The following is a property reference for the Object.\n\n### methods\n\nType: `Array`  \nDefault: `[ 'GET', 'HEAD' ]`\n\nThis property allows a user to pass the list of HTTP request methods accepted by the middleware\\*\\*.\n\n### headers\n\nType: `Array|Object|Function`\nDefault: `undefined`\n\nThis property allows a user to pass custom HTTP headers on each request.\neg. `{ \"X-Custom-Header\": \"yes\" }`\n\nor\n\n```js\nwebpackDevMiddleware(compiler, {\n  headers: () =\u003e {\n    return {\n      \"Last-Modified\": new Date(),\n    };\n  },\n});\n```\n\nor\n\n```js\nwebpackDevMiddleware(compiler, {\n  headers: (req, res, context) =\u003e {\n    res.setHeader(\"Last-Modified\", new Date());\n  },\n});\n```\n\nor\n\n```js\nwebpackDevMiddleware(compiler, {\n  headers: [\n    {\n      key: \"X-custom-header\",\n      value: \"foo\",\n    },\n    {\n      key: \"Y-custom-header\",\n      value: \"bar\",\n    },\n  ],\n});\n```\n\nor\n\n```js\nwebpackDevMiddleware(compiler, {\n  headers: () =\u003e [\n    {\n      key: \"X-custom-header\",\n      value: \"foo\",\n    },\n    {\n      key: \"Y-custom-header\",\n      value: \"bar\",\n    },\n  ],\n});\n```\n\n### index\n\nType: `Boolean|String`\nDefault: `index.html`\n\nIf `false` (but not `undefined`), the server will not respond to requests to the root URL.\n\n### mimeTypes\n\nType: `Object`  \nDefault: `undefined`\n\nThis property allows a user to register custom mime types or extension mappings.\neg. `mimeTypes: { phtml: 'text/html' }`.\n\nPlease see the documentation for [`mime-types`](https://github.com/jshttp/mime-types) for more information.\n\n### mimeTypeDefault\n\nType: `String`  \nDefault: `undefined`\n\nThis property allows a user to register a default mime type when we can't determine the content type.\n\n### etag\n\nType: `\"weak\" | \"strong\"`  \nDefault: `undefined`\n\nEnable or disable etag generation. Boolean value use\n\n### lastModified\n\nType: `Boolean`\nDefault: `undefined`\n\nEnable or disable `Last-Modified` header. Uses the file system's last modified value.\n\n### cacheControl\n\nType: `Boolean | Number | String | { maxAge?: number, immutable?: boolean }`\nDefault: `undefined`\n\nDepending on the setting, the following headers will be generated:\n\n- `Boolean` - `Cache-Control: public, max-age=31536000000`\n- `Number` - `Cache-Control: public, max-age=YOUR_NUMBER`\n- `String` - `Cache-Control: YOUR_STRING`\n- `{ maxAge?: number, immutable?: boolean }` - `Cache-Control: public, max-age=YOUR_MAX_AGE_or_31536000000`, also `, immutable` can be added if you set the `immutable` option to `true`\n\nEnable or disable setting `Cache-Control` response header.\n\n### cacheImmutable\n\nType: `Boolean`\nDefault: `undefined`\n\nEnable or disable setting `Cache-Control: public, max-age=31536000, immutable` response header for immutable assets (i.e. asset with a hash like `image.a4c12bde.jpg`).\nImmutable 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.\nTake preference over the `cacheControl` option if the asset was defined as immutable.\n\n### publicPath\n\nType: `String`\nDefault: `output.publicPath` (from a configuration)\n\nThe public path that the middleware is bound to.\n\n_Best Practice: use the same `publicPath` defined in your webpack config. For more information about `publicPath`, please see [the webpack documentation](https://webpack.js.org/guides/public-path)._\n\n### stats\n\nType: `Boolean|String|Object`\nDefault: `stats` (from a configuration)\n\nStats options object or preset name.\n\n### serverSideRender\n\nType: `Boolean`  \nDefault: `undefined`\n\nInstructs the module to enable or disable the server-side rendering mode.\nPlease see [Server-Side Rendering](#server-side-rendering) for more information.\n\n### writeToDisk\n\nType: `Boolean|Function`  \nDefault: `false`\n\nIf `true`, the option will instruct the module to write files to the configured location on disk as specified in your `webpack` config file.\n_Setting `writeToDisk: true` won't change the behavior of the `webpack-dev-middleware`, and bundle files accessed through the browser will still be served from memory._\nThis option provides the same capabilities as the [`WriteFilePlugin`](https://github.com/gajus/write-file-webpack-plugin/pulls).\n\nThis option also accepts a `Function` value, which can be used to filter which files are written to disk.\nThe function follows the same premise as [`Array#filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter) in which a return value of `false` _will not_ write the file, and a return value of `true` _will_ write the file to disk. eg.\n\n```js\nconst webpack = require(\"webpack\");\nconst configuration = {\n  /* Webpack configuration */\n};\nconst compiler = webpack(configuration);\n\nmiddleware(compiler, {\n  writeToDisk: (filePath) =\u003e {\n    return /superman\\.css$/.test(filePath);\n  },\n});\n```\n\n### outputFileSystem\n\nType: `Object`  \nDefault: [memfs](https://github.com/streamich/memfs)\n\nSet the default file system which will be used by webpack as primary destination of generated files.\nThis option isn't affected by the [writeToDisk](#writeToDisk) option.\n\nYou have to provide `.join()` and `mkdirp` method to the `outputFileSystem` instance manually for compatibility with `webpack@4`.\n\nThis can be done simply by using `path.join`:\n\n```js\nconst webpack = require(\"webpack\");\nconst path = require(\"path\");\nconst myOutputFileSystem = require(\"my-fs\");\nconst mkdirp = require(\"mkdirp\");\n\nmyOutputFileSystem.join = path.join.bind(path); // no need to bind\nmyOutputFileSystem.mkdirp = mkdirp.bind(mkdirp); // no need to bind\n\nconst compiler = webpack({\n  /* Webpack configuration */\n});\n\nmiddleware(compiler, { outputFileSystem: myOutputFileSystem });\n```\n\n### modifyResponseData\n\nAllows to set up a callback to change the response data.\n\n```js\nconst webpack = require(\"webpack\");\nconst configuration = {\n  /* Webpack configuration */\n};\nconst compiler = webpack(configuration);\n\nmiddleware(compiler, {\n  // Note - if you send the `Range` header you will have `ReadStream`\n  // Also `data` can be `string` or `Buffer`\n  modifyResponseData: (req, res, data, byteLength) =\u003e {\n    // Your logic\n    // Don't use `res.end()` or `res.send()` here\n    return { data, byteLength };\n  },\n});\n```\n\n## API\n\n`webpack-dev-middleware` also provides convenience methods that can be use to\ninteract with the middleware at runtime:\n\n### `close(callback)`\n\nInstructs `webpack-dev-middleware` instance to stop watching for file changes.\n\n#### Parameters\n\n##### `callback`\n\nType: `Function`\nRequired: `No`\n\nA function executed once the middleware has stopped watching.\n\n```js\nconst express = require(\"express\");\nconst webpack = require(\"webpack\");\nconst compiler = webpack({\n  /* Webpack configuration */\n});\nconst middleware = require(\"webpack-dev-middleware\");\nconst instance = middleware(compiler);\n\nconst app = new express();\n\napp.use(instance);\n\nsetTimeout(() =\u003e {\n  // Says `webpack` to stop watch changes\n  instance.close();\n}, 1000);\n```\n\n### `invalidate(callback)`\n\nInstructs `webpack-dev-middleware` instance to recompile the bundle, e.g. after a change to the configuration.\n\n#### Parameters\n\n##### `callback`\n\nType: `Function`\nRequired: `No`\n\nA function executed once the middleware has invalidated.\n\n```js\nconst express = require(\"express\");\nconst webpack = require(\"webpack\");\nconst compiler = webpack({\n  /* Webpack configuration */\n});\nconst middleware = require(\"webpack-dev-middleware\");\nconst instance = middleware(compiler);\n\nconst app = new express();\n\napp.use(instance);\n\nsetTimeout(() =\u003e {\n  // After a short delay the configuration is changed and a banner plugin is added to the config\n  new webpack.BannerPlugin(\"A new banner\").apply(compiler);\n\n  // Recompile the bundle with the banner plugin:\n  instance.invalidate();\n}, 1000);\n```\n\n### `waitUntilValid(callback)`\n\nExecutes a callback function when the compiler bundle is valid, typically after\ncompilation.\n\n#### Parameters\n\n##### `callback`\n\nType: `Function`\nRequired: `No`\n\nA function executed when the bundle becomes valid.\nIf the bundle is valid at the time of calling, the callback is executed immediately.\n\n```js\nconst express = require(\"express\");\nconst webpack = require(\"webpack\");\nconst compiler = webpack({\n  /* Webpack configuration */\n});\nconst middleware = require(\"webpack-dev-middleware\");\nconst instance = middleware(compiler);\n\nconst app = new express();\n\napp.use(instance);\n\ninstance.waitUntilValid(() =\u003e {\n  console.log(\"Package is in a valid state\");\n});\n```\n\n### `getFilenameFromUrl(url)`\n\nGet filename from URL.\n\n#### Parameters\n\n##### `url`\n\nType: `String`\nRequired: `Yes`\n\nURL for the requested file.\n\n```js\nconst express = require(\"express\");\nconst webpack = require(\"webpack\");\nconst compiler = webpack({\n  /* Webpack configuration */\n});\nconst middleware = require(\"webpack-dev-middleware\");\nconst instance = middleware(compiler);\n\nconst app = new express();\n\napp.use(instance);\n\ninstance.waitUntilValid(() =\u003e {\n  const filename = instance.getFilenameFromUrl(\"/bundle.js\");\n\n  console.log(`Filename is ${filename}`);\n});\n```\n\n## FAQ\n\n### Avoid blocking requests to non-webpack resources.\n\nSince `output.publicPath` and `output.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.\n\nBut there is a solution to avoid it - mount the middleware to a non-root route, for example:\n\n```js\nconst webpack = require(\"webpack\");\nconst middleware = require(\"webpack-dev-middleware\");\nconst compiler = webpack({\n  // webpack options\n});\nconst express = require(\"express\");\nconst app = express();\n\n// Mounting the middleware to the non-root route allows avoids this.\n// Note - check your public path, if you want to handle `/dist/`, you need to setup `output.publicPath` to `/` value.\napp.use(\n  \"/dist/\",\n  middleware(compiler, {\n    // webpack-dev-middleware options\n  }),\n);\n\napp.listen(3000, () =\u003e console.log(\"Example app listening on port 3000!\"));\n```\n\n## Server-Side Rendering\n\n_Note: this feature is experimental and may be removed or changed completely in the future._\n\nIn order to develop an app using server-side rendering, we need access to the\n[`stats`](https://github.com/webpack/docs/wiki/node.js-api#stats), which is\ngenerated with each build.\n\nWith server-side rendering enabled, `webpack-dev-middleware` sets the `stats` to `res.locals.webpack.devMiddleware.stats`\nand the filesystem to `res.locals.webpack.devMiddleware.outputFileSystem` before invoking the next middleware,\nallowing a developer to render the page body and manage the response to clients.\n\n_Note: Requests for bundle files will still be handled by\n`webpack-dev-middleware` and all requests will be pending until the build\nprocess is finished with server-side rendering enabled._\n\nExample Implementation:\n\n```js\nconst express = require(\"express\");\nconst webpack = require(\"webpack\");\nconst compiler = webpack({\n  /* Webpack configuration */\n});\nconst isObject = require(\"is-object\");\nconst middleware = require(\"webpack-dev-middleware\");\n\nconst app = new express();\n\n// This function makes server rendering of asset references consistent with different webpack chunk/entry configurations\nfunction normalizeAssets(assets) {\n  if (isObject(assets)) {\n    return Object.values(assets);\n  }\n\n  return Array.isArray(assets) ? assets : [assets];\n}\n\napp.use(middleware(compiler, { serverSideRender: true }));\n\n// The following middleware would not be invoked until the latest build is finished.\napp.use((req, res) =\u003e {\n  const { devMiddleware } = res.locals.webpack;\n  const outputFileSystem = devMiddleware.outputFileSystem;\n  const jsonWebpackStats = devMiddleware.stats.toJson();\n  const { assetsByChunkName, outputPath } = jsonWebpackStats;\n\n  // Then use `assetsByChunkName` for server-side rendering\n  // For example, if you have only one main chunk:\n  res.send(`\n\u003chtml\u003e\n  \u003chead\u003e\n    \u003ctitle\u003eMy App\u003c/title\u003e\n    \u003cstyle\u003e\n    ${normalizeAssets(assetsByChunkName.main)\n      .filter((path) =\u003e path.endsWith(\".css\"))\n      .map((path) =\u003e outputFileSystem.readFileSync(path.join(outputPath, path)))\n      .join(\"\\n\")}\n    \u003c/style\u003e\n  \u003c/head\u003e\n  \u003cbody\u003e\n    \u003cdiv id=\"root\"\u003e\u003c/div\u003e\n    ${normalizeAssets(assetsByChunkName.main)\n      .filter((path) =\u003e path.endsWith(\".js\"))\n      .map((path) =\u003e `\u003cscript src=\"${path}\"\u003e\u003c/script\u003e`)\n      .join(\"\\n\")}\n  \u003c/body\u003e\n\u003c/html\u003e\n  `);\n});\n```\n\n## Support\n\nWe do our best to keep Issues in the repository focused on bugs, features, and\nneeded modifications to the code for the module. Because of that, we ask users\nwith general support, \"how-to\", or \"why isn't this working\" questions to try one\nof the other support channels that are available.\n\nYour first-stop-shop for support for webpack-dev-server should by the excellent\n[documentation][docs-url] for the module. If you see an opportunity for improvement\nof those docs, please head over to the [webpack.js.org repo][wjo-url] and open a\npull request.\n\nFrom there, we encourage users to visit the [webpack discussions][chat-url] and\ntalk to the fine folks there. If your quest for answers comes up dry in chat,\nhead over to [StackOverflow][stack-url] and do a quick search or open a new\nquestion. Remember; It's always much easier to answer questions that include your\n`webpack.config.js` and relevant files!\n\nIf you're twitter-savvy you can tweet [#webpack][hash-url] with your question\nand someone should be able to reach out and lend a hand.\n\nIf you have discovered a :bug:, have a feature suggestion, or would like to see\na modification, please feel free to create an issue on Github. _Note: The issue\ntemplate isn't optional, so please be sure not to remove it, and please fill it\nout completely._\n\n## Other servers\n\nExamples of use with other servers will follow here.\n\n### Connect\n\n```js\nconst connect = require(\"connect\");\nconst http = require(\"http\");\nconst webpack = require(\"webpack\");\nconst webpackConfig = require(\"./webpack.config.js\");\nconst devMiddleware = require(\"webpack-dev-middleware\");\n\nconst compiler = webpack(webpackConfig);\nconst devMiddlewareOptions = {\n  /** Your webpack-dev-middleware-options */\n};\nconst app = connect();\n\napp.use(devMiddleware(compiler, devMiddlewareOptions));\n\nhttp.createServer(app).listen(3000);\n```\n\n### Router\n\n```js\nconst http = require(\"http\");\nconst Router = require(\"router\");\nconst finalhandler = require(\"finalhandler\");\nconst webpack = require(\"webpack\");\nconst webpackConfig = require(\"./webpack.config.js\");\nconst devMiddleware = require(\"webpack-dev-middleware\");\n\nconst compiler = webpack(webpackConfig);\nconst devMiddlewareOptions = {\n  /** Your webpack-dev-middleware-options */\n};\nconst router = Router();\n\nrouter.use(devMiddleware(compiler, devMiddlewareOptions));\n\nvar server = http.createServer((req, res) =\u003e {\n  router(req, res, finalhandler(req, res));\n});\n\nserver.listen(3000);\n```\n\n### Express\n\n```js\nconst express = require(\"express\");\nconst webpack = require(\"webpack\");\nconst webpackConfig = require(\"./webpack.config.js\");\nconst devMiddleware = require(\"webpack-dev-middleware\");\n\nconst compiler = webpack(webpackConfig);\nconst devMiddlewareOptions = {\n  /** Your webpack-dev-middleware-options */\n};\nconst app = express();\n\napp.use(devMiddleware(compiler, devMiddlewareOptions));\n\napp.listen(3000, () =\u003e console.log(\"Example app listening on port 3000!\"));\n```\n\n### Koa\n\n```js\nconst Koa = require(\"koa\");\nconst webpack = require(\"webpack\");\nconst webpackConfig = require(\"./webpack.simple.config\");\nconst middleware = require(\"webpack-dev-middleware\");\n\nconst compiler = webpack(webpackConfig);\nconst devMiddlewareOptions = {\n  /** Your webpack-dev-middleware-options */\n};\nconst app = new Koa();\n\napp.use(middleware.koaWrapper(compiler, devMiddlewareOptions));\n\napp.listen(3000);\n```\n\n### Hapi\n\n```js\nconst Hapi = require(\"@hapi/hapi\");\nconst webpack = require(\"webpack\");\nconst webpackConfig = require(\"./webpack.config.js\");\nconst devMiddleware = require(\"webpack-dev-middleware\");\n\nconst compiler = webpack(webpackConfig);\nconst devMiddlewareOptions = {};\n\n(async () =\u003e {\n  const server = Hapi.server({ port: 3000, host: \"localhost\" });\n\n  await server.register({\n    plugin: devMiddleware.hapiPlugin(),\n    options: {\n      // The `compiler` option is required\n      compiler,\n      ...devMiddlewareOptions,\n    },\n  });\n\n  await server.start();\n\n  console.log(\"Server running on %s\", server.info.uri);\n})();\n\nprocess.on(\"unhandledRejection\", (err) =\u003e {\n  console.log(err);\n  process.exit(1);\n});\n```\n\n### Fastify\n\nFastify interop will require the use of `fastify-express` instead of `middie` for providing middleware support. As the authors of `fastify-express` recommend, this should only be used as a stopgap while full Fastify support is worked on.\n\n```js\nconst fastify = require(\"fastify\")();\nconst webpack = require(\"webpack\");\nconst webpackConfig = require(\"./webpack.config.js\");\nconst devMiddleware = require(\"webpack-dev-middleware\");\n\nconst compiler = webpack(webpackConfig);\nconst devMiddlewareOptions = {\n  /** Your webpack-dev-middleware-options */\n};\n\n(async () =\u003e {\n  await fastify.register(require(\"@fastify/express\"));\n  await fastify.use(devMiddleware(compiler, devMiddlewareOptions));\n  await fastify.listen(3000);\n})();\n```\n\n### Hono\n\n```js\nimport webpack from \"webpack\";\nimport { serve } from \"@hono/node-server\";\nimport { Hono } from \"hono\";\nimport devMiddleware from \"webpack-dev-middleware\";\nimport webpackConfig from \"./webpack.config.js\";\n\nconst compiler = webpack(webpackConfig);\nconst devMiddlewareOptions = {\n  /** Your webpack-dev-middleware-options */\n};\n\nconst app = new Hono();\n\napp.use(devMiddleware.honoWrapper(compiler, devMiddlewareOptions));\n\nserve(app);\n```\n\n## Contributing\n\nPlease take a moment to read our contributing guidelines if you haven't yet done so.\n\n[CONTRIBUTING](./CONTRIBUTING.md)\n\n## License\n\n[MIT](./LICENSE)\n\n[npm]: https://img.shields.io/npm/v/webpack-dev-middleware.svg\n[npm-url]: https://npmjs.com/package/webpack-dev-middleware\n[node]: https://img.shields.io/node/v/webpack-dev-middleware.svg\n[node-url]: https://nodejs.org\n[tests]: https://github.com/webpack/webpack-dev-middleware/workflows/webpack-dev-middleware/badge.svg\n[tests-url]: https://github.com/webpack/webpack-dev-middleware/actions\n[cover]: https://codecov.io/gh/webpack/webpack-dev-middleware/branch/master/graph/badge.svg\n[cover-url]: https://codecov.io/gh/webpack/webpack-dev-middleware\n[discussion]: https://img.shields.io/github/discussions/webpack/webpack\n[discussion-url]: https://github.com/webpack/webpack/discussions\n[size]: https://packagephobia.com/badge?p=webpack-dev-middleware\n[size-url]: https://packagephobia.com/result?p=webpack-dev-middleware\n[docs-url]: https://webpack.js.org/guides/development/#using-webpack-dev-middleware\n[hash-url]: https://twitter.com/search?q=webpack\n[middleware-url]: https://github.com/webpack/webpack-dev-middleware\n[stack-url]: https://stackoverflow.com/questions/tagged/webpack-dev-middleware\n[chat-url]: https://github.com/webpack/webpack/discussions\n[wjo-url]: https://github.com/webpack/webpack.js.org\n","funding_links":["https://opencollective.com/webpack"],"categories":["webpack","JavaScript","打包工具"],"sub_categories":["webpack 辅助工具、Loader 和插件"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwebpack%2Fwebpack-dev-middleware","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwebpack%2Fwebpack-dev-middleware","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwebpack%2Fwebpack-dev-middleware/lists"}