Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

README.md 13 KiB

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