• Home
  • History
  • Annotate
Name Date Size #Lines LOC

..03-May-2022-

CHANGELOG.mdH A D01-Jan-19704.7 KiB11448

LICENSEH A D01-Jan-19701 KiB2117

README.mdH A D01-Jan-197014.1 KiB452328

README.md

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