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.

451 lines
14 KiB

4 years 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. ## Requirements
  23. This module requires a minimum of Node v6.9.0 and Webpack v4.0.0, and must be used with a
  24. server that accepts express-style middleware.
  25. ## Getting Started
  26. First thing's first, install the module:
  27. ```console
  28. npm install webpack-dev-middleware --save-dev
  29. ```
  30. _Note: We do not recommend installing this module globally._
  31. ## Usage
  32. ```js
  33. const webpack = require('webpack');
  34. const middleware = require('webpack-dev-middleware');
  35. const compiler = webpack({
  36. // webpack options
  37. });
  38. const express = require('express');
  39. const app = express();
  40. app.use(
  41. middleware(compiler, {
  42. // webpack-dev-middleware options
  43. })
  44. );
  45. app.listen(3000, () => console.log('Example app listening on port 3000!'));
  46. ```
  47. ## Options
  48. The middleware accepts an `options` Object. The following is a property reference
  49. for the Object.
  50. _Note: The `publicPath` property is required, whereas all other options are optional_
  51. ### methods
  52. Type: `Array`
  53. Default: `[ 'GET', 'HEAD' ]`
  54. This property allows a user to pass the list of HTTP request methods accepted by the server.
  55. ### headers
  56. Type: `Object`
  57. Default: `undefined`
  58. This property allows a user to pass custom HTTP headers on each request. eg.
  59. `{ "X-Custom-Header": "yes" }`
  60. ### index
  61. Type: `String`
  62. Default: `undefined`
  63. "index.html",
  64. // The index path for web server, defaults to "index.html".
  65. // If falsy (but not undefined), the server will not respond to requests to the root URL.
  66. ### lazy
  67. Type: `Boolean`
  68. Default: `undefined`
  69. This option instructs the module to operate in 'lazy' mode, meaning that it won't
  70. recompile when files change, but rather on each request.
  71. ### logger
  72. Type: `Object`
  73. Default: [`webpack-log`](https://github.com/webpack-contrib/webpack-log/blob/master/index.js)
  74. In the rare event that a user would like to provide a custom logging interface,
  75. this property allows the user to assign one. The module leverages
  76. [`webpack-log`](https://github.com/webpack-contrib/webpack-log#readme)
  77. for creating the [`loglevelnext`](https://github.com/shellscape/loglevelnext#readme)
  78. logging management by default. Any custom logger must adhere to the same
  79. exports for compatibility. Specifically, all custom loggers must have the
  80. following exported methods at a minimum:
  81. - `log.trace`
  82. - `log.debug`
  83. - `log.info`
  84. - `log.warn`
  85. - `log.error`
  86. Please see the documentation for `loglevel` for more information.
  87. ### logLevel
  88. Type: `String`
  89. Default: `'info'`
  90. This property defines the level of messages that the module will log. Valid levels
  91. include:
  92. - `trace`
  93. - `debug`
  94. - `info`
  95. - `warn`
  96. - `error`
  97. - `silent`
  98. Setting a log level means that all other levels below it will be visible in the
  99. console. Setting `logLevel: 'silent'` will hide all console output. The module
  100. leverages [`webpack-log`](https://github.com/webpack-contrib/webpack-log#readme)
  101. for logging management, and more information can be found on its page.
  102. ### logTime
  103. Type: `Boolean`
  104. Default: `false`
  105. If `true` the log output of the module will be prefixed by a timestamp in the
  106. `HH:mm:ss` format.
  107. ### mimeTypes
  108. Type: `Object`
  109. Default: `null`
  110. This property allows a user to register custom mime types or extension mappings.
  111. eg. `mimeTypes: { 'text/html': [ 'phtml' ] }`.
  112. By default node-mime will throw an error if you try to map a type to an extension
  113. that is already assigned to another type. Passing `force: true` will suppress this behavior
  114. (overriding any previous mapping).
  115. eg. `mimeTypes: { typeMap: { 'text/html': [ 'phtml' ] } }, force: true }`.
  116. Please see the documentation for
  117. [`node-mime`](https://github.com/broofa/node-mime#mimedefinetypemap-force--false) for more information.
  118. ### publicPath
  119. Type: `String`
  120. _Required_
  121. The public path that the middleware is bound to. _Best Practice: use the same
  122. `publicPath` defined in your webpack config. For more information about
  123. `publicPath`, please see
  124. [the webpack documentation](https://webpack.js.org/guides/public-path)._
  125. ### reporter
  126. Type: `Object`
  127. Default: `undefined`
  128. Allows users to provide a custom reporter to handle logging within the module.
  129. Please see the [default reporter](/lib/reporter.js)
  130. for an example.
  131. ### serverSideRender
  132. Type: `Boolean`
  133. Default: `undefined`
  134. Instructs the module to enable or disable the server-side rendering mode. Please
  135. see [Server-Side Rendering](#server-side-rendering) for more information.
  136. ### stats
  137. Type: `Object`
  138. Default: `{ context: process.cwd() }`
  139. Options for formatting statistics displayed during and after compile. For more
  140. information and property details, please see the
  141. [webpack documentation](https://webpack.js.org/configuration/stats/#stats).
  142. ### watchOptions
  143. Type: `Object`
  144. Default: `{ aggregateTimeout: 200 }`
  145. The module accepts an `Object` containing options for file watching, which is
  146. passed directly to the compiler provided. For more information on watch options
  147. please see the [webpack documentation](https://webpack.js.org/configuration/watch/#watchoptions)
  148. ### writeToDisk
  149. Type: `Boolean|Function`
  150. Default: `false`
  151. If `true`, the option will instruct the module to write files to the configured
  152. location on disk as specified in your `webpack` config file. _Setting
  153. `writeToDisk: true` won't change the behavior of the `webpack-dev-middleware`,
  154. and bundle files accessed through the browser will still be served from memory._
  155. This option provides the same capabilities as the
  156. [`WriteFilePlugin`](https://github.com/gajus/write-file-webpack-plugin/pulls).
  157. This option also accepts a `Function` value, which can be used to filter which
  158. files are written to disk. The function follows the same premise as
  159. [`Array#filter`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter)
  160. in which a return value of `false` _will not_ write the file, and a return value
  161. of `true` _will_ write the file to disk. eg.
  162. ```js
  163. {
  164. writeToDisk: (filePath) => {
  165. return /superman\.css$/.test(filePath);
  166. };
  167. }
  168. ```
  169. ### fs
  170. Type: `Object`
  171. Default: `MemoryFileSystem`
  172. Set the default file system which will be used by webpack as primary destination of generated files. Default is set to webpack's default file system: [memory-fs](https://github.com/webpack/memory-fs). This option isn't affected by the [writeToDisk](#writeToDisk) option.
  173. **Note:** As of 3.5.x version of the middleware you have to provide `.join()` method to the `fs` instance manually. This can be done simply by using `path.join`:
  174. ```js
  175. fs.join = path.join; // no need to bind
  176. ```
  177. ## API
  178. `webpack-dev-middleware` also provides convenience methods that can be use to
  179. interact with the middleware at runtime:
  180. ### `close(callback)`
  181. Instructs a webpack-dev-middleware instance to stop watching for file changes.
  182. ### Parameters
  183. #### callback
  184. Type: `Function`
  185. A function executed once the middleware has stopped watching.
  186. ### `invalidate()`
  187. Instructs a webpack-dev-middleware instance to recompile the bundle.
  188. e.g. after a change to the configuration.
  189. ```js
  190. const webpack = require('webpack');
  191. const compiler = webpack({ ... });
  192. const middleware = require('webpack-dev-middleware');
  193. const instance = middleware(compiler);
  194. app.use(instance);
  195. setTimeout(() => {
  196. // After a short delay the configuration is changed and a banner plugin is added
  197. // to the config
  198. compiler.apply(new webpack.BannerPlugin('A new banner'));
  199. // Recompile the bundle with the banner plugin:
  200. instance.invalidate();
  201. }, 1000);
  202. ```
  203. ### `waitUntilValid(callback)`
  204. Executes a callback function when the compiler bundle is valid, typically after
  205. compilation.
  206. ### Parameters
  207. #### callback
  208. Type: `Function`
  209. A function executed when the bundle becomes valid. If the bundle is
  210. valid at the time of calling, the callback is executed immediately.
  211. ```js
  212. const webpack = require('webpack');
  213. const compiler = webpack({ ... });
  214. const middleware = require('webpack-dev-middleware');
  215. const instance = middleware(compiler);
  216. app.use(instance);
  217. instance.waitUntilValid(() => {
  218. console.log('Package is in a valid state');
  219. });
  220. ```
  221. ## Known Issues
  222. ### Multiple Successive Builds
  223. Watching (by means of `lazy: false`) will frequently cause multiple compilations
  224. as the bundle changes during compilation. This is due in part to cross-platform
  225. differences in file watchers, so that webpack doesn't loose file changes when
  226. watched files change rapidly. If you run into this situation, please make use of
  227. the [`TimeFixPlugin`](https://github.com/egoist/time-fix-plugin).
  228. ## Server-Side Rendering
  229. _Note: this feature is experimental and may be removed or changed completely in the future._
  230. In order to develop an app using server-side rendering, we need access to the
  231. [`stats`](https://github.com/webpack/docs/wiki/node.js-api#stats), which is
  232. generated with each build.
  233. With server-side rendering enabled, `webpack-dev-middleware` sets the `stat` to
  234. `res.locals.webpackStats` and the memory filesystem to `res.locals.fs` before invoking the next middleware, allowing a
  235. developer to render the page body and manage the response to clients.
  236. _Note: Requests for bundle files will still be handled by
  237. `webpack-dev-middleware` and all requests will be pending until the build
  238. process is finished with server-side rendering enabled._
  239. Example Implementation:
  240. ```js
  241. const webpack = require('webpack');
  242. const compiler = webpack({
  243. // webpack options
  244. });
  245. const isObject = require('is-object');
  246. const middleware = require('webpack-dev-middleware');
  247. // This function makes server rendering of asset references consistent with different webpack chunk/entry configurations
  248. function normalizeAssets(assets) {
  249. if (isObject(assets)) {
  250. return Object.values(assets);
  251. }
  252. return Array.isArray(assets) ? assets : [assets];
  253. }
  254. app.use(middleware(compiler, { serverSideRender: true }));
  255. // The following middleware would not be invoked until the latest build is finished.
  256. app.use((req, res) => {
  257. const assetsByChunkName = res.locals.webpackStats.toJson().assetsByChunkName;
  258. const fs = res.locals.fs;
  259. const outputPath = res.locals.webpackStats.toJson().outputPath;
  260. // then use `assetsByChunkName` for server-sider rendering
  261. // For example, if you have only one main chunk:
  262. res.send(`
  263. <html>
  264. <head>
  265. <title>My App</title>
  266. <style>
  267. ${normalizeAssets(assetsByChunkName.main)
  268. .filter((path) => path.endsWith('.css'))
  269. .map((path) => fs.readFileSync(outputPath + '/' + path))
  270. .join('\n')}
  271. </style>
  272. </head>
  273. <body>
  274. <div id="root"></div>
  275. ${normalizeAssets(assetsByChunkName.main)
  276. .filter((path) => path.endsWith('.js'))
  277. .map((path) => `<script src="${path}"></script>`)
  278. .join('\n')}
  279. </body>
  280. </html>
  281. `);
  282. });
  283. ```
  284. ## Support
  285. We do our best to keep Issues in the repository focused on bugs, features, and
  286. needed modifications to the code for the module. Because of that, we ask users
  287. with general support, "how-to", or "why isn't this working" questions to try one
  288. of the other support channels that are available.
  289. Your first-stop-shop for support for webpack-dev-server should by the excellent
  290. [documentation][docs-url] for the module. If you see an opportunity for improvement
  291. of those docs, please head over to the [webpack.js.org repo][wjo-url] and open a
  292. pull request.
  293. From there, we encourage users to visit the [webpack Gitter chat][chat-url] and
  294. talk to the fine folks there. If your quest for answers comes up dry in chat,
  295. head over to [StackOverflow][stack-url] and do a quick search or open a new
  296. question. Remember; It's always much easier to answer questions that include your
  297. `webpack.config.js` and relevant files!
  298. If you're twitter-savvy you can tweet [#webpack][hash-url] with your question
  299. and someone should be able to reach out and lend a hand.
  300. If you have discovered a :bug:, have a feature suggestion, or would like to see
  301. a modification, please feel free to create an issue on Github. _Note: The issue
  302. template isn't optional, so please be sure not to remove it, and please fill it
  303. out completely._
  304. ## Contributing
  305. Please take a moment to read our contributing guidelines if you haven't yet done so.
  306. [CONTRIBUTING](./.github/CONTRIBUTING.md)
  307. ## License
  308. [MIT](./LICENSE)
  309. [npm]: https://img.shields.io/npm/v/webpack-dev-middleware.svg
  310. [npm-url]: https://npmjs.com/package/webpack-dev-middleware
  311. [node]: https://img.shields.io/node/v/webpack-dev-middleware.svg
  312. [node-url]: https://nodejs.org
  313. [deps]: https://david-dm.org/webpack/webpack-dev-middleware.svg
  314. [deps-url]: https://david-dm.org/webpack/webpack-dev-middleware
  315. [tests]: https://dev.azure.com/webpack/webpack-dev-middleware/_apis/build/status/webpack.webpack-dev-middleware?branchName=master
  316. [tests-url]: https://dev.azure.com/webpack/webpack-dev-middleware/_build/latest?definitionId=8&branchName=master
  317. [cover]: https://codecov.io/gh/webpack/webpack-dev-middleware/branch/master/graph/badge.svg
  318. [cover-url]: https://codecov.io/gh/webpack/webpack-dev-middleware
  319. [chat]: https://badges.gitter.im/webpack/webpack.svg
  320. [chat-url]: https://gitter.im/webpack/webpack
  321. [size]: https://packagephobia.now.sh/badge?p=webpack-dev-middleware
  322. [size-url]: https://packagephobia.now.sh/result?p=webpack-dev-middleware
  323. [docs-url]: https://webpack.js.org/guides/development/#using-webpack-dev-middleware
  324. [hash-url]: https://twitter.com/search?q=webpack
  325. [middleware-url]: https://github.com/webpack/webpack-dev-middleware
  326. [stack-url]: https://stackoverflow.com/questions/tagged/webpack-dev-middleware
  327. [uglify-url]: https://github.com/webpack-contrib/uglifyjs-webpack-plugin
  328. [wjo-url]: https://github.com/webpack/webpack.js.org