{"name":"webpack-dev-middleware","version":"7.4.3","keywords":["webpack","middleware","development"],"author":{"name":"Tobias Koppers @sokra"},"license":"MIT","_id":"webpack-dev-middleware@7.4.3","maintainers":[{"name":"sokra","email":"tobias.koppers@googlemail.com"},{"name":"jhnns","email":"mail@johannesewald.de"},{"name":"evilebottnawi","email":"sheo13666q@gmail.com"},{"name":"hiroppy","email":"git@hiroppy.me"}],"homepage":"https://github.com/webpack/webpack-dev-middleware","bugs":{"url":"https://github.com/webpack/webpack-dev-middleware/issues"},"dist":{"shasum":"4e23b479a574549334641faa4e00670720f01839","tarball":"http://registry-npm.ywwl.com/webpack-dev-middleware/download/webpack-dev-middleware-7.4.3.tgz","fileCount":30,"integrity":"sha512-5kA/PzpZzDz5mNOkcNLmU1UdjGeSSxd7rt1akWpI70jMNHLASiBPRaQZn0hgyhvhawfIwSnnLfDABIxL3ueyFg==","signatures":[{"sig":"MEYCIQDQpL99siyxZM7x/3K/hvYAJa+SLYSt37gO6kjJlEVaGgIhAL7nfsgGKU8Kp5nMQCBGJTZhieQ8awo8yA2Am3xmVAgv","keyid":"SHA256:DhQ8wR5APBvFHLF/+Tc+AYvPOdTpcIDqOhxsBHRwC7U"}],"unpackedSize":142881,"size":30650,"noattachment":false,"key":"/webpack-dev-middleware/-/webpack-dev-middleware-7.4.3.tgz"},"main":"dist/index.js","types":"types/index.d.ts","engines":{"node":">= 18.12.0"},"funding":{"url":"https://opencollective.com/webpack","type":"opencollective"},"gitHead":"fd5e61ce45349e03ef911db02824ecaee6e48ba1","scripts":{"fix":"npm-run-all -l fix:js fix:prettier","lint":"npm-run-all -l -p \"lint:**\"","test":"npm run test:coverage","build":"npm-run-all -p \"build:**\"","clean":"del-cli dist types","fix:js":"npm run lint:code -- --fix","prepare":"husky && npm run build","pretest":"npm run lint","release":"standard-version","prebuild":"npm run clean","security":"npm audit --production","lint:code":"eslint --cache .","test:only":"cross-env NODE_ENV=test jest","build:code":"cross-env NODE_ENV=production babel src -d dist --copy-files","commitlint":"commitlint --from=master","lint:types":"tsc --pretty --noEmit","test:watch":"npm run test:only -- --watch","build:types":"tsc --declaration --emitDeclarationOnly --outDir types && prettier \"types/**/*.ts\" --write","fix:prettier":"npm run lint:prettier -- --write","lint:prettier":"prettier --cache --list-different .","lint:spelling":"cspell --cache --no-must-find-files --quiet \"**/*.*\"","test:coverage":"npm run test:only -- --collectCoverageFrom=\"src/**/*.js\" --coverage"},"_npmUser":{"name":"evilebottnawi","email":"sheo13666q@gmail.com"},"repository":{"url":"git+https://github.com/webpack/webpack-dev-middleware.git","type":"git"},"_npmVersion":"10.9.2","description":"A development middleware for webpack","directories":{},"_nodeVersion":"22.15.1","dependencies":{"memfs":"^4.6.0","colorette":"^2.0.10","mime-types":"^3.0.1","on-finished":"^2.4.1","range-parser":"^1.2.1","schema-utils":"^4.0.0"},"_hasShrinkwrap":false,"devDependencies":{"joi":"^17.12.2","koa":"^3.0.0","hono":"^4.4.13","jest":"^29.3.1","execa":"^5.1.1","husky":"^9.1.3","cspell":"^8.3.2","eslint":"^9.28.0","router":"^2.2.0","connect":"^3.7.0","del-cli":"^6.0.0","express":"^5.1.0","fastify":"^5.2.1","globals":"^16.2.0","webpack":"^5.101.0","prettier":"^3.6.0","cross-env":"^7.0.3","deepmerge":"^4.2.2","express-4":"npm:express@^4","supertest":"^7.0.0","@babel/cli":"^7.16.7","@eslint/js":"^9.28.0","@hapi/hapi":"^21.3.7","babel-jest":"^29.3.1","strip-ansi":"^6.0.0","typescript":"^5.3.3","@babel/core":"^7.16.7","@types/node":"^22.3.0","file-loader":"^6.2.0","lint-staged":"^15.2.0","npm-run-all":"^4.1.5","finalhandler":"^2.1.0","@types/connect":"^3.4.35","@types/express":"^5.0.2","@commitlint/cli":"^19.0.3","eslint-plugin-n":"^17.19.0","@eslint/markdown":"^7.1.0","@fastify/express":"^4.0.2","standard-version":"^9.3.0","@babel/preset-env":"^7.16.7","@hono/node-server":"^1.12.0","@types/mime-types":"^2.1.1","@types/on-finished":"^2.3.4","eslint-plugin-jest":"^28.12.0","eslint-plugin-jsdoc":"^50.7.1","eslint-plugin-import":"^2.31.0","eslint-config-webpack":"^4.5.0","eslint-plugin-unicorn":"^60.0.0","eslint-config-prettier":"^10.1.5","eslint-plugin-prettier":"^5.4.1","@stylistic/eslint-plugin":"^4.4.1","@commitlint/config-conventional":"^19.0.3"},"peerDependencies":{"webpack":"^5.0.0"},"peerDependenciesMeta":{"webpack":{"optional":true}},"_npmOperationalInternal":{"tmp":"tmp/webpack-dev-middleware_7.4.3_1757065577918_0.2229134708430629","host":"s3://npm-registry-packages-npm-production"},"readme":"<div align=\"center\">\n  <a href=\"https://github.com/webpack/webpack\">\n    <img width=\"200\" height=\"200\" src=\"https://webpack.js.org/assets/icon-square-big.svg\">\n  </a>\n</div>\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> [!WARNING]\n>\n> _We do not recommend installing this module globally._\n\n## Usage\n\n```js\nconst express = require(\"express\");\nconst webpack = require(\"webpack\");\nconst middleware = require(\"webpack-dev-middleware\");\n\nconst compiler = webpack({\n  // webpack options\n});\n\nconst app = express();\n\napp.use(\n  middleware(compiler, {\n    // webpack-dev-middleware options\n  }),\n);\n\napp.listen(3000, () => 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|       **[`forwardError`](#forwarderror)**       |             `boolean`             |                    `false`                    | Enable or disable forwarding errors to the next middleware.                                                          |\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: () => ({\n    \"Last-Modified\": new Date(),\n  }),\n});\n```\n\nor\n\n```js\nwebpackDevMiddleware(compiler, {\n  headers: (req, res, context) => {\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: () => [\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\");\n\nconst configuration = {\n  /* Webpack configuration */\n};\nconst compiler = webpack(configuration);\n\nmiddleware(compiler, {\n  writeToDisk: (filePath) => /superman\\.css$/.test(filePath),\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 path = require(\"node:path\");\nconst mkdirp = require(\"mkdirp\");\nconst myOutputFileSystem = require(\"my-fs\");\nconst webpack = require(\"webpack\");\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\");\n\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) =>\n    // Your logic\n    // Don't use `res.end()` or `res.send()` here\n    ({ data, byteLength }),\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\");\n\nconst compiler = webpack({\n  /* Webpack configuration */\n});\n\nconst middleware = require(\"webpack-dev-middleware\");\n\nconst instance = middleware(compiler);\n\n// eslint-disable-next-line new-cap\nconst app = new express();\n\napp.use(instance);\n\nsetTimeout(() => {\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\");\n\nconst compiler = webpack({\n  /* Webpack configuration */\n});\n\nconst middleware = require(\"webpack-dev-middleware\");\n\nconst instance = middleware(compiler);\n\n// eslint-disable-next-line new-cap\nconst app = new express();\n\napp.use(instance);\n\nsetTimeout(() => {\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\");\n\nconst compiler = webpack({\n  /* Webpack configuration */\n});\n\nconst middleware = require(\"webpack-dev-middleware\");\n\nconst instance = middleware(compiler);\n\n// eslint-disable-next-line new-cap\nconst app = new express();\n\napp.use(instance);\n\ninstance.waitUntilValid(() => {\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\");\n\nconst compiler = webpack({\n  /* Webpack configuration */\n});\n\nconst middleware = require(\"webpack-dev-middleware\");\n\nconst instance = middleware(compiler);\n\n// eslint-disable-next-line new-cap\nconst app = new express();\n\napp.use(instance);\n\ninstance.waitUntilValid(() => {\n  instance\n    .getFilenameFromUrl(\"/bundle.js\")\n    .then((filename) => {\n      if (!filename) {\n        return;\n      }\n\n      console.log(`Filename is ${filename}`);\n    })\n    .catch((err) => {\n      console.log(`Error: ${err}`);\n    });\n});\n```\n\n### `plugin(compiler, options)`\n\nCreates middleware instance in plugin mode.\n\nIn plugin mode, stats output is written through custom code (i.e. in callback for `watch` or where you are calling `stats.toString(options)`) instead of `console.log`.\nIn this case, the `stats` option is not supported because `webpack-dev-middleware` does not have access to the code where the stats will be output.\nYou will also need to manually run the `watch` method.\n\nWhy do you need this mode? In some cases, you may want to have multiple dev servers or run only one dev server when you have multiple configurations, and this is suitable for you.\n\n```js\nconst webpack = require(\"webpack\");\nconst middleware = require(\"webpack-dev-middleware\");\n\nconst compiler = webpack({\n  plugins: [\n    {\n      apply(compiler) {\n        const devMiddleware = middleware(\n          compiler,\n          {\n            /* webpack-dev-middleware options */\n          },\n          true,\n        );\n      },\n    },\n  ],\n  /* Webpack configuration */\n});\n\ncompiler.watch((err, stats) => {\n  if (err) {\n    console.error(err);\n    return;\n  }\n\n  console.log(stats.toString());\n});\n```\n\n### Plugin wrappers\n\nThe following wrappers enable plugin mode for framework integrations:\n\n- `middleware(compiler, options, true)` (connect/express like middleware)\n- `middleware.koaWrapper(compiler, options, true)`\n- `middleware.hapiWrapper(true)`\n- `middleware.honoWrapper(compiler, options, true)`\n\nThey are equivalent to `koaWrapper`/`hapiWrapper`/`honoWrapper`, but use plugin mode logging behavior.\n\n### `forwardError`\n\nType: `boolean`\nDefault: `false`\n\nEnable or disable forwarding errors to the next middleware. If `true`, errors will be forwarded to the next middleware, otherwise, they will be handled by `webpack-dev-middleware` and a response will be handled case by case.\n\nThis option don't work with hono, koa and hapi, because of the differences in error handling between these frameworks and express.\n\n```js\nconst express = require(\"express\");\nconst webpack = require(\"webpack\");\nconst middleware = require(\"webpack-dev-middleware\");\n\nconst compiler = webpack({\n  /* Webpack configuration */\n});\n\nconst instance = middleware(compiler, { forwardError: true });\n\nconst app = express();\napp.use(instance);\n\napp.use((err, req, res, next) => {\n  console.log(`Error: ${err}`);\n  res.status(500).send(\"Something broke!\");\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 express = require(\"express\");\nconst webpack = require(\"webpack\");\nconst middleware = require(\"webpack-dev-middleware\");\n\nconst compiler = webpack({\n  // webpack options\n});\n\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, () => 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 isObject = require(\"is-object\");\nconst webpack = require(\"webpack\");\nconst middleware = require(\"webpack-dev-middleware\");\n\nconst compiler = webpack({\n  /* Webpack configuration */\n});\n\n// eslint-disable-next-line new-cap\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) => {\n  const { devMiddleware } = res.locals.webpack;\n  const { outputFileSystem } = devMiddleware;\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<html>\n  <head>\n    <title>My App</title>\n    <style>\n    ${normalizeAssets(assetsByChunkName.main)\n      .filter((path) => path.endsWith(\".css\"))\n      .map((path) => outputFileSystem.readFileSync(path.join(outputPath, path)))\n      .join(\"\\n\")}\n    </style>\n  </head>\n  <body>\n    <div id=\"root\"></div>\n    ${normalizeAssets(assetsByChunkName.main)\n      .filter((path) => path.endsWith(\".js\"))\n      .map((path) => `<script src=\"${path}\"></script>`)\n      .join(\"\\n\")}\n  </body>\n</html>\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 http = require(\"node:http\");\nconst connect = require(\"connect\");\nconst webpack = require(\"webpack\");\nconst devMiddleware = require(\"webpack-dev-middleware\");\nconst webpackConfig = require(\"./webpack.config.js\");\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(\"node:http\");\nconst finalhandler = require(\"finalhandler\");\nconst Router = require(\"router\");\nconst webpack = require(\"webpack\");\nconst devMiddleware = require(\"webpack-dev-middleware\");\nconst webpackConfig = require(\"./webpack.config.js\");\n\nconst compiler = webpack(webpackConfig);\nconst devMiddlewareOptions = {\n  /** Your webpack-dev-middleware-options */\n};\n\n// eslint-disable-next-line new-cap\nconst router = Router();\n\nrouter.use(devMiddleware(compiler, devMiddlewareOptions));\n\nconst server = http.createServer((req, res) => {\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 devMiddleware = require(\"webpack-dev-middleware\");\nconst webpackConfig = require(\"./webpack.config.js\");\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, () => console.log(\"Example app listening on port 3000!\"));\n```\n\n### Koa\n\n```js\nconst Koa = require(\"koa\");\nconst webpack = require(\"webpack\");\nconst middleware = require(\"webpack-dev-middleware\");\nconst webpackConfig = require(\"./webpack.simple.config\");\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// Alternative usage (when you want to use as a plugin, i.e. all stats will be printed by other code):\n// app.use(middleware.koaWrapper(compiler, devMiddlewareOptions, true));\n\napp.listen(3000);\n```\n\n### Hapi\n\n```js\nconst Hapi = require(\"@hapi/hapi\");\nconst webpack = require(\"webpack\");\nconst devMiddleware = require(\"webpack-dev-middleware\");\nconst webpackConfig = require(\"./webpack.config.js\");\n\nconst compiler = webpack(webpackConfig);\nconst devMiddlewareOptions = {};\n\nconst server = Hapi.server({ port: 3000, host: \"localhost\" });\n\nawait server.register({\n  plugin: devMiddleware.hapiWrapper(),\n  options: {\n    // The `compiler` option is required\n    compiler,\n    ...devMiddlewareOptions,\n  },\n});\n\n// Alternative usage (when you want to use as a plugin, i.e. all stats will be printed by other code):\n// await server.register({\n//   plugin: devMiddleware.hapiWrapper(true),\n//   options: {\n//     // The `compiler` option is required\n//     compiler,\n//     ...devMiddlewareOptions,\n//   },\n// });\n\nawait server.start();\n\nconsole.log(\"Server running on %s\", server.info.uri);\n\nprocess.on(\"unhandledRejection\", (err) => {\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 devMiddleware = require(\"webpack-dev-middleware\");\nconst webpackConfig = require(\"./webpack.config.js\");\n\nconst compiler = webpack(webpackConfig);\nconst devMiddlewareOptions = {\n  /** Your webpack-dev-middleware-options */\n};\n\nawait fastify.register(require(\"@fastify/express\"));\nawait fastify.use(devMiddleware(compiler, devMiddlewareOptions));\nawait fastify.listen(3000);\n```\n\n### Hono\n\n```js\nimport { serve } from \"@hono/node-server\";\nimport { Hono } from \"hono\";\nimport webpack from \"webpack\";\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\n// Alternative usage (when you want to use as a plugin, i.e. all stats will be printed by other code):\n// const honoDevMiddleware = devMiddleware.honoWrapper(compiler, devMiddlewareOptions, true)\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](https://github.com/webpack/sass-loader?tab=contributing-ov-file#contributing)\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/main/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","publish_time":1757065578129,"_cnpm_publish_time":1757065578129,"dist-tags":{"latest":"8.6.0","next":"4.0.0-rc.3","version-5":"5.3.4","version-6":"6.1.3","version-7":"7.4.6"}}