You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

542 lines
17 KiB

3 months ago
  1. <div align="center">
  2. <a href="https://github.com/webpack/webpack">
  3. <img width="200" height="200" src="https://webpack.js.org/assets/icon-square-big.svg">
  4. </a>
  5. </div>
  6. [![npm][npm]][npm-url]
  7. [![node][node]][node-url]
  8. [![deps][deps]][deps-url]
  9. [![tests][tests]][tests-url]
  10. [![coverage][cover]][cover-url]
  11. [![chat][chat]][chat-url]
  12. [![size][size]][size-url]
  13. # webpack-dev-middleware
  14. An express-style development middleware for use with [webpack](https://webpack.js.org)
  15. bundles and allows for serving of the files emitted from webpack.
  16. This should be used for **development only**.
  17. Some of the benefits of using this middleware include:
  18. - No files are written to disk, rather it handles files in memory
  19. - If files changed in watch mode, the middleware delays requests until compiling
  20. has completed.
  21. - Supports hot module reload (HMR).
  22. ## Getting Started
  23. First thing's first, install the module:
  24. ```console
  25. npm install webpack-dev-middleware --save-dev
  26. ```
  27. _Note: We do not recommend installing this module globally._
  28. ## Usage
  29. ```js
  30. const webpack = require("webpack");
  31. const middleware = require("webpack-dev-middleware");
  32. const compiler = webpack({
  33. // webpack options
  34. });
  35. const express = require("express");
  36. const app = express();
  37. app.use(
  38. middleware(compiler, {
  39. // webpack-dev-middleware options
  40. })
  41. );
  42. app.listen(3000, () => console.log("Example app listening on port 3000!"));
  43. ```
  44. See [below](#other-servers) for an example of use with fastify.
  45. ## Options
  46. | Name | Type | Default | Description |
  47. | :-----------------------------------------: | :-----------------------: | :-------------------------------------------: | :------------------------------------------------------------------------------------------------------------------- |
  48. | **[`methods`](#methods)** | `Array` | `[ 'GET', 'HEAD' ]` | Allows to pass the list of HTTP request methods accepted by the middleware |
  49. | **[`headers`](#headers)** | `Array\|Object\|Function` | `undefined` | Allows to pass custom HTTP headers on each request. |
  50. | **[`index`](#index)** | `Boolean\|String` | `index.html` | If `false` (but not `undefined`), the server will not respond to requests to the root URL. |
  51. | **[`mimeTypes`](#mimetypes)** | `Object` | `undefined` | Allows to register custom mime types or extension mappings. |
  52. | **[`publicPath`](#publicpath)** | `String` | `output.publicPath` (from a configuration) | The public path that the middleware is bound to. |
  53. | **[`stats`](#stats)** | `Boolean\|String\|Object` | `stats` (from a configuration) | Stats options object or preset name. |
  54. | **[`serverSideRender`](#serversiderender)** | `Boolean` | `undefined` | Instructs the module to enable or disable the server-side rendering mode. |
  55. | **[`writeToDisk`](#writetodisk)** | `Boolean\|Function` | `false` | Instructs the module to write files to the configured location on disk as specified in your `webpack` configuration. |
  56. | **[`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. |
  57. The middleware accepts an `options` Object. The following is a property reference for the Object.
  58. ### methods
  59. Type: `Array`
  60. Default: `[ 'GET', 'HEAD' ]`
  61. This property allows a user to pass the list of HTTP request methods accepted by the middleware\*\*.
  62. ### headers
  63. Type: `Array|Object|Function`
  64. Default: `undefined`
  65. This property allows a user to pass custom HTTP headers on each request.
  66. eg. `{ "X-Custom-Header": "yes" }`
  67. or
  68. ```js
  69. webpackDevMiddleware(compiler, {
  70. headers: () => {
  71. return {
  72. "Last-Modified": new Date(),
  73. };
  74. },
  75. });
  76. ```
  77. or
  78. ```js
  79. webpackDevMiddleware(compiler, {
  80. headers: (req, res, context) => {
  81. res.setHeader("Last-Modified", new Date());
  82. },
  83. });
  84. ```
  85. or
  86. ```js
  87. webpackDevMiddleware(compiler, {
  88. headers: [
  89. {
  90. key: "X-custom-header"
  91. value: "foo"
  92. },
  93. {
  94. key: "Y-custom-header",
  95. value: "bar"
  96. }
  97. ]
  98. },
  99. });
  100. ```
  101. or
  102. ```js
  103. webpackDevMiddleware(compiler, {
  104. headers: () => [
  105. {
  106. key: "X-custom-header"
  107. value: "foo"
  108. },
  109. {
  110. key: "Y-custom-header",
  111. value: "bar"
  112. }
  113. ]
  114. },
  115. });
  116. ```
  117. ### index
  118. Type: `Boolean|String`
  119. Default: `index.html`
  120. If `false` (but not `undefined`), the server will not respond to requests to the root URL.
  121. ### mimeTypes
  122. Type: `Object`
  123. Default: `undefined`
  124. This property allows a user to register custom mime types or extension mappings.
  125. eg. `mimeTypes: { phtml: 'text/html' }`.
  126. Please see the documentation for [`mime-types`](https://github.com/jshttp/mime-types) for more information.
  127. ### publicPath
  128. Type: `String`
  129. Default: `output.publicPath` (from a configuration)
  130. The public path that the middleware is bound to.
  131. _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)._
  132. ### stats
  133. Type: `Boolean|String|Object`
  134. Default: `stats` (from a configuration)
  135. Stats options object or preset name.
  136. ### serverSideRender
  137. Type: `Boolean`
  138. Default: `undefined`
  139. Instructs the module to enable or disable the server-side rendering mode.
  140. Please see [Server-Side Rendering](#server-side-rendering) for more information.
  141. ### writeToDisk
  142. Type: `Boolean|Function`
  143. Default: `false`
  144. If `true`, the option will instruct the module to write files to the configured location on disk as specified in your `webpack` config file.
  145. _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._
  146. This option provides the same capabilities as the [`WriteFilePlugin`](https://github.com/gajus/write-file-webpack-plugin/pulls).
  147. This option also accepts a `Function` value, which can be used to filter which files are written to disk.
  148. The 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.
  149. ```js
  150. const webpack = require("webpack");
  151. const configuration = {
  152. /* Webpack configuration */
  153. };
  154. const compiler = webpack(configuration);
  155. middleware(compiler, {
  156. writeToDisk: (filePath) => {
  157. return /superman\.css$/.test(filePath);
  158. },
  159. });
  160. ```
  161. ### outputFileSystem
  162. Type: `Object`
  163. Default: [memfs](https://github.com/streamich/memfs)
  164. Set the default file system which will be used by webpack as primary destination of generated files.
  165. This option isn't affected by the [writeToDisk](#writeToDisk) option.
  166. You have to provide `.join()` and `mkdirp` method to the `outputFileSystem` instance manually for compatibility with `webpack@4`.
  167. This can be done simply by using `path.join`:
  168. ```js
  169. const webpack = require("webpack");
  170. const path = require("path");
  171. const myOutputFileSystem = require("my-fs");
  172. const mkdirp = require("mkdirp");
  173. myOutputFileSystem.join = path.join.bind(path); // no need to bind
  174. myOutputFileSystem.mkdirp = mkdirp.bind(mkdirp); // no need to bind
  175. const compiler = webpack({
  176. /* Webpack configuration */
  177. });
  178. middleware(compiler, { outputFileSystem: myOutputFileSystem });
  179. ```
  180. ## API
  181. `webpack-dev-middleware` also provides convenience methods that can be use to
  182. interact with the middleware at runtime:
  183. ### `close(callback)`
  184. Instructs `webpack-dev-middleware` instance to stop watching for file changes.
  185. #### Parameters
  186. ##### `callback`
  187. Type: `Function`
  188. Required: `No`
  189. A function executed once the middleware has stopped watching.
  190. ```js
  191. const express = require("express");
  192. const webpack = require("webpack");
  193. const compiler = webpack({
  194. /* Webpack configuration */
  195. });
  196. const middleware = require("webpack-dev-middleware");
  197. const instance = middleware(compiler);
  198. const app = new express();
  199. app.use(instance);
  200. setTimeout(() => {
  201. // Says `webpack` to stop watch changes
  202. instance.close();
  203. }, 1000);
  204. ```
  205. ### `invalidate(callback)`
  206. Instructs `webpack-dev-middleware` instance to recompile the bundle, e.g. after a change to the configuration.
  207. #### Parameters
  208. ##### `callback`
  209. Type: `Function`
  210. Required: `No`
  211. A function executed once the middleware has invalidated.
  212. ```js
  213. const express = require("express");
  214. const webpack = require("webpack");
  215. const compiler = webpack({
  216. /* Webpack configuration */
  217. });
  218. const middleware = require("webpack-dev-middleware");
  219. const instance = middleware(compiler);
  220. const app = new express();
  221. app.use(instance);
  222. setTimeout(() => {
  223. // After a short delay the configuration is changed and a banner plugin is added to the config
  224. new webpack.BannerPlugin("A new banner").apply(compiler);
  225. // Recompile the bundle with the banner plugin:
  226. instance.invalidate();
  227. }, 1000);
  228. ```
  229. ### `waitUntilValid(callback)`
  230. Executes a callback function when the compiler bundle is valid, typically after
  231. compilation.
  232. #### Parameters
  233. ##### `callback`
  234. Type: `Function`
  235. Required: `No`
  236. A function executed when the bundle becomes valid.
  237. If the bundle is valid at the time of calling, the callback is executed immediately.
  238. ```js
  239. const express = require("express");
  240. const webpack = require("webpack");
  241. const compiler = webpack({
  242. /* Webpack configuration */
  243. });
  244. const middleware = require("webpack-dev-middleware");
  245. const instance = middleware(compiler);
  246. const app = new express();
  247. app.use(instance);
  248. instance.waitUntilValid(() => {
  249. console.log("Package is in a valid state");
  250. });
  251. ```
  252. ### `getFilenameFromUrl(url)`
  253. Get filename from URL.
  254. #### Parameters
  255. ##### `url`
  256. Type: `String`
  257. Required: `Yes`
  258. URL for the requested file.
  259. ```js
  260. const express = require("express");
  261. const webpack = require("webpack");
  262. const compiler = webpack({
  263. /* Webpack configuration */
  264. });
  265. const middleware = require("webpack-dev-middleware");
  266. const instance = middleware(compiler);
  267. const app = new express();
  268. app.use(instance);
  269. instance.waitUntilValid(() => {
  270. const filename = instance.getFilenameFromUrl("/bundle.js");
  271. console.log(`Filename is ${filename}`);
  272. });
  273. ```
  274. ## Known Issues
  275. ### Multiple Successive Builds
  276. Watching will frequently cause multiple compilations
  277. as the bundle changes during compilation. This is due in part to cross-platform
  278. differences in file watchers, so that webpack doesn't loose file changes when
  279. watched files change rapidly. If you run into this situation, please make use of
  280. the [`TimeFixPlugin`](https://github.com/egoist/time-fix-plugin).
  281. ## Server-Side Rendering
  282. _Note: this feature is experimental and may be removed or changed completely in the future._
  283. In order to develop an app using server-side rendering, we need access to the
  284. [`stats`](https://github.com/webpack/docs/wiki/node.js-api#stats), which is
  285. generated with each build.
  286. With server-side rendering enabled, `webpack-dev-middleware` sets the `stats` to `res.locals.webpack.devMiddleware.context.stats`
  287. and the filesystem to `res.locals.webpack.devMiddleware.context.outputFileSystem` before invoking the next middleware,
  288. allowing a developer to render the page body and manage the response to clients.
  289. _Note: Requests for bundle files will still be handled by
  290. `webpack-dev-middleware` and all requests will be pending until the build
  291. process is finished with server-side rendering enabled._
  292. Example Implementation:
  293. ```js
  294. const express = require("express");
  295. const webpack = require("webpack");
  296. const compiler = webpack({
  297. /* Webpack configuration */
  298. });
  299. const isObject = require("is-object");
  300. const middleware = require("webpack-dev-middleware");
  301. const app = new express();
  302. // This function makes server rendering of asset references consistent with different webpack chunk/entry configurations
  303. function normalizeAssets(assets) {
  304. if (isObject(assets)) {
  305. return Object.values(assets);
  306. }
  307. return Array.isArray(assets) ? assets : [assets];
  308. }
  309. app.use(middleware(compiler, { serverSideRender: true }));
  310. // The following middleware would not be invoked until the latest build is finished.
  311. app.use((req, res) => {
  312. const { devMiddleware } = res.locals.webpack;
  313. const outputFileSystem = devMiddleware.context.outputFileSystem;
  314. const jsonWebpackStats = devMiddleware.context.stats.toJson();
  315. const { assetsByChunkName, outputPath } = jsonWebpackStats;
  316. // Then use `assetsByChunkName` for server-side rendering
  317. // For example, if you have only one main chunk:
  318. res.send(`
  319. <html>
  320. <head>
  321. <title>My App</title>
  322. <style>
  323. ${normalizeAssets(assetsByChunkName.main)
  324. .filter((path) => path.endsWith(".css"))
  325. .map((path) => outputFileSystem.readFileSync(path.join(outputPath, path)))
  326. .join("\n")}
  327. </style>
  328. </head>
  329. <body>
  330. <div id="root"></div>
  331. ${normalizeAssets(assetsByChunkName.main)
  332. .filter((path) => path.endsWith(".js"))
  333. .map((path) => `<script src="${path}"></script>`)
  334. .join("\n")}
  335. </body>
  336. </html>
  337. `);
  338. });
  339. ```
  340. ## Support
  341. We do our best to keep Issues in the repository focused on bugs, features, and
  342. needed modifications to the code for the module. Because of that, we ask users
  343. with general support, "how-to", or "why isn't this working" questions to try one
  344. of the other support channels that are available.
  345. Your first-stop-shop for support for webpack-dev-server should by the excellent
  346. [documentation][docs-url] for the module. If you see an opportunity for improvement
  347. of those docs, please head over to the [webpack.js.org repo][wjo-url] and open a
  348. pull request.
  349. From there, we encourage users to visit the [webpack Gitter chat][chat-url] and
  350. talk to the fine folks there. If your quest for answers comes up dry in chat,
  351. head over to [StackOverflow][stack-url] and do a quick search or open a new
  352. question. Remember; It's always much easier to answer questions that include your
  353. `webpack.config.js` and relevant files!
  354. If you're twitter-savvy you can tweet [#webpack][hash-url] with your question
  355. and someone should be able to reach out and lend a hand.
  356. If you have discovered a :bug:, have a feature suggestion, or would like to see
  357. a modification, please feel free to create an issue on Github. _Note: The issue
  358. template isn't optional, so please be sure not to remove it, and please fill it
  359. out completely._
  360. ## Other servers
  361. Examples of use with other servers will follow here.
  362. ### Fastify
  363. Fastify 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.
  364. ```js
  365. const fastify = require("fastify")();
  366. const webpack = require("webpack");
  367. const webpackConfig = require("./webpack.config.js");
  368. const devMiddleware = require("webpack-dev-middleware");
  369. const compiler = webpack(webpackConfig);
  370. const { publicPath } = webpackConfig.output;
  371. (async () => {
  372. await fastify.register(require("fastify-express"));
  373. await fastify.use(devMiddleware(compiler, { publicPath }));
  374. await fastify.listen(3000);
  375. })();
  376. ```
  377. ## Contributing
  378. Please take a moment to read our contributing guidelines if you haven't yet done so.
  379. [CONTRIBUTING](./CONTRIBUTING.md)
  380. ## License
  381. [MIT](./LICENSE)
  382. [npm]: https://img.shields.io/npm/v/webpack-dev-middleware.svg
  383. [npm-url]: https://npmjs.com/package/webpack-dev-middleware
  384. [node]: https://img.shields.io/node/v/webpack-dev-middleware.svg
  385. [node-url]: https://nodejs.org
  386. [deps]: https://david-dm.org/webpack/webpack-dev-middleware.svg
  387. [deps-url]: https://david-dm.org/webpack/webpack-dev-middleware
  388. [tests]: https://github.com/webpack/webpack-dev-middleware/workflows/webpack-dev-middleware/badge.svg
  389. [tests-url]: https://github.com/webpack/webpack-dev-middleware/actions
  390. [cover]: https://codecov.io/gh/webpack/webpack-dev-middleware/branch/master/graph/badge.svg
  391. [cover-url]: https://codecov.io/gh/webpack/webpack-dev-middleware
  392. [chat]: https://badges.gitter.im/webpack/webpack.svg
  393. [chat-url]: https://gitter.im/webpack/webpack
  394. [size]: https://packagephobia.com/badge?p=webpack-dev-middleware
  395. [size-url]: https://packagephobia.com/result?p=webpack-dev-middleware
  396. [docs-url]: https://webpack.js.org/guides/development/#using-webpack-dev-middleware
  397. [hash-url]: https://twitter.com/search?q=webpack
  398. [middleware-url]: https://github.com/webpack/webpack-dev-middleware
  399. [stack-url]: https://stackoverflow.com/questions/tagged/webpack-dev-middleware
  400. [wjo-url]: https://github.com/webpack/webpack.js.org