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 |
|
17 | An express-style development middleware for use with [webpack](https://webpack.js.org)
|
18 | bundles and allows for serving of the files emitted from webpack.
|
19 | This should be used for **development only**.
|
20 |
|
21 | Some 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 |
|
30 | First thing's first, install the module:
|
31 |
|
32 | ```console
|
33 | npm install webpack-dev-middleware --save-dev
|
34 | ```
|
35 |
|
36 | _Note: We do not recommend installing this module globally._
|
37 |
|
38 | ## Usage
|
39 |
|
40 | ```js
|
41 | const webpack = require("webpack");
|
42 | const middleware = require("webpack-dev-middleware");
|
43 | const compiler = webpack({
|
44 | // webpack options
|
45 | });
|
46 | const express = require("express");
|
47 | const app = express();
|
48 |
|
49 | app.use(
|
50 | middleware(compiler, {
|
51 | // webpack-dev-middleware options
|
52 | })
|
53 | );
|
54 |
|
55 | app.listen(3000, () => console.log("Example app listening on port 3000!"));
|
56 | ```
|
57 |
|
58 | See [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 |
|
74 | The middleware accepts an `options` Object. The following is a property reference for the Object.
|
75 |
|
76 | ### methods
|
77 |
|
78 | Type: `Array`
|
79 | Default: `[ 'GET', 'HEAD' ]`
|
80 |
|
81 | This property allows a user to pass the list of HTTP request methods accepted by the middleware\*\*.
|
82 |
|
83 | ### headers
|
84 |
|
85 | Type: `Array|Object|Function`
|
86 | Default: `undefined`
|
87 |
|
88 | This property allows a user to pass custom HTTP headers on each request.
|
89 | eg. `{ "X-Custom-Header": "yes" }`
|
90 |
|
91 | or
|
92 |
|
93 | ```js
|
94 | webpackDevMiddleware(compiler, {
|
95 | headers: () => {
|
96 | return {
|
97 | "Last-Modified": new Date(),
|
98 | };
|
99 | },
|
100 | });
|
101 | ```
|
102 |
|
103 | or
|
104 |
|
105 | ```js
|
106 | webpackDevMiddleware(compiler, {
|
107 | headers: (req, res, context) => {
|
108 | res.setHeader("Last-Modified", new Date());
|
109 | },
|
110 | });
|
111 | ```
|
112 |
|
113 | or
|
114 |
|
115 | ```js
|
116 | webpackDevMiddleware(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 |
|
131 | or
|
132 |
|
133 | ```js
|
134 | webpackDevMiddleware(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 |
|
151 | Type: `Boolean|String`
|
152 | Default: `index.html`
|
153 |
|
154 | If `false` (but not `undefined`), the server will not respond to requests to the root URL.
|
155 |
|
156 | ### mimeTypes
|
157 |
|
158 | Type: `Object`
|
159 | Default: `undefined`
|
160 |
|
161 | This property allows a user to register custom mime types or extension mappings.
|
162 | eg. `mimeTypes: { phtml: 'text/html' }`.
|
163 |
|
164 | Please see the documentation for [`mime-types`](https://github.com/jshttp/mime-types) for more information.
|
165 |
|
166 | ### publicPath
|
167 |
|
168 | Type: `String`
|
169 | Default: `output.publicPath` (from a configuration)
|
170 |
|
171 | The 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 |
|
177 | Type: `Boolean|String|Object`
|
178 | Default: `stats` (from a configuration)
|
179 |
|
180 | Stats options object or preset name.
|
181 |
|
182 | ### serverSideRender
|
183 |
|
184 | Type: `Boolean`
|
185 | Default: `undefined`
|
186 |
|
187 | Instructs the module to enable or disable the server-side rendering mode.
|
188 | Please see [Server-Side Rendering](#server-side-rendering) for more information.
|
189 |
|
190 | ### writeToDisk
|
191 |
|
192 | Type: `Boolean|Function`
|
193 | Default: `false`
|
194 |
|
195 | If `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._
|
197 | This option provides the same capabilities as the [`WriteFilePlugin`](https://github.com/gajus/write-file-webpack-plugin/pulls).
|
198 |
|
199 | This option also accepts a `Function` value, which can be used to filter which files are written to disk.
|
200 | 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.
|
201 |
|
202 | ```js
|
203 | const webpack = require("webpack");
|
204 | const configuration = {
|
205 | /* Webpack configuration */
|
206 | };
|
207 | const compiler = webpack(configuration);
|
208 |
|
209 | middleware(compiler, {
|
210 | writeToDisk: (filePath) => {
|
211 | return /superman\.css$/.test(filePath);
|
212 | },
|
213 | });
|
214 | ```
|
215 |
|
216 | ### outputFileSystem
|
217 |
|
218 | Type: `Object`
|
219 | Default: [memfs](https://github.com/streamich/memfs)
|
220 |
|
221 | Set the default file system which will be used by webpack as primary destination of generated files.
|
222 | This option isn't affected by the [writeToDisk](#writeToDisk) option.
|
223 |
|
224 | You have to provide `.join()` and `mkdirp` method to the `outputFileSystem` instance manually for compatibility with `webpack@4`.
|
225 |
|
226 | This can be done simply by using `path.join`:
|
227 |
|
228 | ```js
|
229 | const webpack = require("webpack");
|
230 | const path = require("path");
|
231 | const myOutputFileSystem = require("my-fs");
|
232 | const mkdirp = require("mkdirp");
|
233 |
|
234 | myOutputFileSystem.join = path.join.bind(path); // no need to bind
|
235 | myOutputFileSystem.mkdirp = mkdirp.bind(mkdirp); // no need to bind
|
236 |
|
237 | const compiler = webpack({
|
238 | /* Webpack configuration */
|
239 | });
|
240 |
|
241 | middleware(compiler, { outputFileSystem: myOutputFileSystem });
|
242 | ```
|
243 |
|
244 | ## API
|
245 |
|
246 | `webpack-dev-middleware` also provides convenience methods that can be use to
|
247 | interact with the middleware at runtime:
|
248 |
|
249 | ### `close(callback)`
|
250 |
|
251 | Instructs `webpack-dev-middleware` instance to stop watching for file changes.
|
252 |
|
253 | #### Parameters
|
254 |
|
255 | ##### `callback`
|
256 |
|
257 | Type: `Function`
|
258 | Required: `No`
|
259 |
|
260 | A function executed once the middleware has stopped watching.
|
261 |
|
262 | ```js
|
263 | const express = require("express");
|
264 | const webpack = require("webpack");
|
265 | const compiler = webpack({
|
266 | /* Webpack configuration */
|
267 | });
|
268 | const middleware = require("webpack-dev-middleware");
|
269 | const instance = middleware(compiler);
|
270 |
|
271 | const app = new express();
|
272 |
|
273 | app.use(instance);
|
274 |
|
275 | setTimeout(() => {
|
276 | // Says `webpack` to stop watch changes
|
277 | instance.close();
|
278 | }, 1000);
|
279 | ```
|
280 |
|
281 | ### `invalidate(callback)`
|
282 |
|
283 | Instructs `webpack-dev-middleware` instance to recompile the bundle, e.g. after a change to the configuration.
|
284 |
|
285 | #### Parameters
|
286 |
|
287 | ##### `callback`
|
288 |
|
289 | Type: `Function`
|
290 | Required: `No`
|
291 |
|
292 | A function executed once the middleware has invalidated.
|
293 |
|
294 | ```js
|
295 | const express = require("express");
|
296 | const webpack = require("webpack");
|
297 | const compiler = webpack({
|
298 | /* Webpack configuration */
|
299 | });
|
300 | const middleware = require("webpack-dev-middleware");
|
301 | const instance = middleware(compiler);
|
302 |
|
303 | const app = new express();
|
304 |
|
305 | app.use(instance);
|
306 |
|
307 | setTimeout(() => {
|
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 |
|
318 | Executes a callback function when the compiler bundle is valid, typically after
|
319 | compilation.
|
320 |
|
321 | #### Parameters
|
322 |
|
323 | ##### `callback`
|
324 |
|
325 | Type: `Function`
|
326 | Required: `No`
|
327 |
|
328 | A function executed when the bundle becomes valid.
|
329 | If the bundle is valid at the time of calling, the callback is executed immediately.
|
330 |
|
331 | ```js
|
332 | const express = require("express");
|
333 | const webpack = require("webpack");
|
334 | const compiler = webpack({
|
335 | /* Webpack configuration */
|
336 | });
|
337 | const middleware = require("webpack-dev-middleware");
|
338 | const instance = middleware(compiler);
|
339 |
|
340 | const app = new express();
|
341 |
|
342 | app.use(instance);
|
343 |
|
344 | instance.waitUntilValid(() => {
|
345 | console.log("Package is in a valid state");
|
346 | });
|
347 | ```
|
348 |
|
349 | ### `getFilenameFromUrl(url)`
|
350 |
|
351 | Get filename from URL.
|
352 |
|
353 | #### Parameters
|
354 |
|
355 | ##### `url`
|
356 |
|
357 | Type: `String`
|
358 | Required: `Yes`
|
359 |
|
360 | URL for the requested file.
|
361 |
|
362 | ```js
|
363 | const express = require("express");
|
364 | const webpack = require("webpack");
|
365 | const compiler = webpack({
|
366 | /* Webpack configuration */
|
367 | });
|
368 | const middleware = require("webpack-dev-middleware");
|
369 | const instance = middleware(compiler);
|
370 |
|
371 | const app = new express();
|
372 |
|
373 | app.use(instance);
|
374 |
|
375 | instance.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 |
|
386 | Watching will frequently cause multiple compilations
|
387 | as the bundle changes during compilation. This is due in part to cross-platform
|
388 | differences in file watchers, so that webpack doesn't loose file changes when
|
389 | watched files change rapidly. If you run into this situation, please make use of
|
390 | the [`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 |
|
396 | In 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
|
398 | generated with each build.
|
399 |
|
400 | With server-side rendering enabled, `webpack-dev-middleware` sets the `stats` to `res.locals.webpack.devMiddleware.context.stats`
|
401 | and the filesystem to `res.locals.webpack.devMiddleware.context.outputFileSystem` before invoking the next middleware,
|
402 | allowing 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
|
406 | process is finished with server-side rendering enabled._
|
407 |
|
408 | Example Implementation:
|
409 |
|
410 | ```js
|
411 | const express = require("express");
|
412 | const webpack = require("webpack");
|
413 | const compiler = webpack({
|
414 | /* Webpack configuration */
|
415 | });
|
416 | const isObject = require("is-object");
|
417 | const middleware = require("webpack-dev-middleware");
|
418 |
|
419 | const app = new express();
|
420 |
|
421 | // This function makes server rendering of asset references consistent with different webpack chunk/entry configurations
|
422 | function normalizeAssets(assets) {
|
423 | if (isObject(assets)) {
|
424 | return Object.values(assets);
|
425 | }
|
426 |
|
427 | return Array.isArray(assets) ? assets : [assets];
|
428 | }
|
429 |
|
430 | app.use(middleware(compiler, { serverSideRender: true }));
|
431 |
|
432 | // The following middleware would not be invoked until the latest build is finished.
|
433 | app.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 |
|
466 | We do our best to keep Issues in the repository focused on bugs, features, and
|
467 | needed modifications to the code for the module. Because of that, we ask users
|
468 | with general support, "how-to", or "why isn't this working" questions to try one
|
469 | of the other support channels that are available.
|
470 |
|
471 | Your 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
|
473 | of those docs, please head over to the [webpack.js.org repo][wjo-url] and open a
|
474 | pull request.
|
475 |
|
476 | From there, we encourage users to visit the [webpack Gitter chat][chat-url] and
|
477 | talk to the fine folks there. If your quest for answers comes up dry in chat,
|
478 | head over to [StackOverflow][stack-url] and do a quick search or open a new
|
479 | question. Remember; It's always much easier to answer questions that include your
|
480 | `webpack.config.js` and relevant files!
|
481 |
|
482 | If you're twitter-savvy you can tweet [#webpack][hash-url] with your question
|
483 | and someone should be able to reach out and lend a hand.
|
484 |
|
485 | If you have discovered a :bug:, have a feature suggestion, or would like to see
|
486 | a modification, please feel free to create an issue on Github. _Note: The issue
|
487 | template isn't optional, so please be sure not to remove it, and please fill it
|
488 | out completely._
|
489 |
|
490 | ## Other servers
|
491 |
|
492 | Examples of use with other servers will follow here.
|
493 |
|
494 | ### Fastify
|
495 |
|
496 | 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.
|
497 |
|
498 | ```js
|
499 | const fastify = require("fastify")();
|
500 | const webpack = require("webpack");
|
501 | const webpackConfig = require("./webpack.config.js");
|
502 | const devMiddleware = require("webpack-dev-middleware");
|
503 |
|
504 | const compiler = webpack(webpackConfig);
|
505 | const { 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 |
|
516 | Please 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
|