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