UNPKG

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