source: trip-planner-front/node_modules/webpack-dev-middleware/README.md@ ceaed42

Last change on this file since ceaed42 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 14.1 KB
Line 
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
62The middleware accepts an `options` Object. The following is a property reference for the Object.
63
64### methods
65
66Type: `Array`
67Default: `[ 'GET', 'HEAD' ]`
68
69This property allows a user to pass the list of HTTP request methods accepted by the middleware\*\*.
70
71### headers
72
73Type: `Object|Function`
74Default: `undefined`
75
76This property allows a user to pass custom HTTP headers on each request.
77eg. `{ "X-Custom-Header": "yes" }`
78
79or
80
81```js
82webpackDevMiddleware(compiler, {
83 headers: () => {
84 return {
85 "Last-Modified": new Date(),
86 };
87 },
88});
89```
90
91or
92
93```js
94webpackDevMiddleware(compiler, {
95 headers: (req, res, context) => {
96 res.setHeader("Last-Modified", new Date());
97 },
98});
99```
100
101### index
102
103Type: `Boolean|String`
104Default: `index.html`
105
106If `false` (but not `undefined`), the server will not respond to requests to the root URL.
107
108### mimeTypes
109
110Type: `Object`
111Default: `undefined`
112
113This property allows a user to register custom mime types or extension mappings.
114eg. `mimeTypes: { phtml: 'text/html' }`.
115
116Please see the documentation for [`mime-types`](https://github.com/jshttp/mime-types) for more information.
117
118### publicPath
119
120Type: `String`
121Default: `output.publicPath` (from a configuration)
122
123The 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
129Type: `Boolean|String|Object`
130Default: `stats` (from a configuration)
131
132Stats options object or preset name.
133
134### serverSideRender
135
136Type: `Boolean`
137Default: `undefined`
138
139Instructs the module to enable or disable the server-side rendering mode.
140Please see [Server-Side Rendering](#server-side-rendering) for more information.
141
142### writeToDisk
143
144Type: `Boolean|Function`
145Default: `false`
146
147If `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._
149This option provides the same capabilities as the [`WriteFilePlugin`](https://github.com/gajus/write-file-webpack-plugin/pulls).
150
151This option also accepts a `Function` value, which can be used to filter which files are written to disk.
152The 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
155const webpack = require("webpack");
156const configuration = {
157 /* Webpack configuration */
158};
159const compiler = webpack(configuration);
160
161middleware(compiler, {
162 writeToDisk: (filePath) => {
163 return /superman\.css$/.test(filePath);
164 },
165});
166```
167
168### outputFileSystem
169
170Type: `Object`
171Default: [memfs](https://github.com/streamich/memfs)
172
173Set the default file system which will be used by webpack as primary destination of generated files.
174This option isn't affected by the [writeToDisk](#writeToDisk) option.
175
176You have to provide `.join()` and `mkdirp` method to the `outputFileSystem` instance manually for compatibility with `webpack@4`.
177
178This can be done simply by using `path.join`:
179
180```js
181const webpack = require("webpack");
182const path = require("path");
183const myOutputFileSystem = require("my-fs");
184const mkdirp = require("mkdirp");
185
186myOutputFileSystem.join = path.join.bind(path); // no need to bind
187myOutputFileSystem.mkdirp = mkdirp.bind(mkdirp); // no need to bind
188
189const compiler = webpack({
190 /* Webpack configuration */
191});
192
193middleware(compiler, { outputFileSystem: myOutputFileSystem });
194```
195
196## API
197
198`webpack-dev-middleware` also provides convenience methods that can be use to
199interact with the middleware at runtime:
200
201### `close(callback)`
202
203Instructs `webpack-dev-middleware` instance to stop watching for file changes.
204
205#### Parameters
206
207##### `callback`
208
209Type: `Function`
210Required: `No`
211
212A function executed once the middleware has stopped watching.
213
214```js
215const express = require("express");
216const webpack = require("webpack");
217const compiler = webpack({
218 /* Webpack configuration */
219});
220const middleware = require("webpack-dev-middleware");
221const instance = middleware(compiler);
222
223const app = new express();
224
225app.use(instance);
226
227setTimeout(() => {
228 // Says `webpack` to stop watch changes
229 instance.close();
230}, 1000);
231```
232
233### `invalidate(callback)`
234
235Instructs `webpack-dev-middleware` instance to recompile the bundle, e.g. after a change to the configuration.
236
237#### Parameters
238
239##### `callback`
240
241Type: `Function`
242Required: `No`
243
244A function executed once the middleware has invalidated.
245
246```js
247const express = require("express");
248const webpack = require("webpack");
249const compiler = webpack({
250 /* Webpack configuration */
251});
252const middleware = require("webpack-dev-middleware");
253const instance = middleware(compiler);
254
255const app = new express();
256
257app.use(instance);
258
259setTimeout(() => {
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
270Executes a callback function when the compiler bundle is valid, typically after
271compilation.
272
273#### Parameters
274
275##### `callback`
276
277Type: `Function`
278Required: `No`
279
280A function executed when the bundle becomes valid.
281If the bundle is valid at the time of calling, the callback is executed immediately.
282
283```js
284const express = require("express");
285const webpack = require("webpack");
286const compiler = webpack({
287 /* Webpack configuration */
288});
289const middleware = require("webpack-dev-middleware");
290const instance = middleware(compiler);
291
292const app = new express();
293
294app.use(instance);
295
296instance.waitUntilValid(() => {
297 console.log("Package is in a valid state");
298});
299```
300
301### `getFilenameFromUrl(url)`
302
303Get filename from URL.
304
305#### Parameters
306
307##### `url`
308
309Type: `String`
310Required: `Yes`
311
312URL for the requested file.
313
314```js
315const express = require("express");
316const webpack = require("webpack");
317const compiler = webpack({
318 /* Webpack configuration */
319});
320const middleware = require("webpack-dev-middleware");
321const instance = middleware(compiler);
322
323const app = new express();
324
325app.use(instance);
326
327instance.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
338Watching will frequently cause multiple compilations
339as the bundle changes during compilation. This is due in part to cross-platform
340differences in file watchers, so that webpack doesn't loose file changes when
341watched files change rapidly. If you run into this situation, please make use of
342the [`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
348In 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
350generated with each build.
351
352With server-side rendering enabled, `webpack-dev-middleware` sets the `stats` to `res.locals.webpack.devMiddleware.stats`
353and the filesystem to `res.locals.webpack.devMiddleware.outputFileSystem` before invoking the next middleware,
354allowing 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
358process is finished with server-side rendering enabled._
359
360Example Implementation:
361
362```js
363const express = require("express");
364const webpack = require("webpack");
365const compiler = webpack({
366 /* Webpack configuration */
367});
368const isObject = require("is-object");
369const middleware = require("webpack-dev-middleware");
370
371const app = new express();
372
373// This function makes server rendering of asset references consistent with different webpack chunk/entry configurations
374function normalizeAssets(assets) {
375 if (isObject(assets)) {
376 return Object.values(assets);
377 }
378
379 return Array.isArray(assets) ? assets : [assets];
380}
381
382app.use(middleware(compiler, { serverSideRender: true }));
383
384// The following middleware would not be invoked until the latest build is finished.
385app.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
418We do our best to keep Issues in the repository focused on bugs, features, and
419needed modifications to the code for the module. Because of that, we ask users
420with general support, "how-to", or "why isn't this working" questions to try one
421of the other support channels that are available.
422
423Your 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
425of those docs, please head over to the [webpack.js.org repo][wjo-url] and open a
426pull request.
427
428From there, we encourage users to visit the [webpack Gitter chat][chat-url] and
429talk to the fine folks there. If your quest for answers comes up dry in chat,
430head over to [StackOverflow][stack-url] and do a quick search or open a new
431question. Remember; It's always much easier to answer questions that include your
432`webpack.config.js` and relevant files!
433
434If you're twitter-savvy you can tweet [#webpack][hash-url] with your question
435and someone should be able to reach out and lend a hand.
436
437If you have discovered a :bug:, have a feature suggestion, or would like to see
438a modification, please feel free to create an issue on Github. _Note: The issue
439template isn't optional, so please be sure not to remove it, and please fill it
440out completely._
441
442## Other servers
443
444Examples of use with other servers will follow here.
445
446### Fastify
447
448Fastify 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
451const fastify = require("fastify")();
452const webpack = require("webpack");
453const webpackConfig = require("./webpack.config.js");
454const devMiddleware = require("webpack-dev-middleware");
455
456const compiler = webpack(webpackConfig);
457const { 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
468Please 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
Note: See TracBrowser for help on using the repository browser.