Projekt

Obecné

Profil

Stáhnout (14.1 KB) Statistiky
| Větev: | Revize:
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
## Requirements
29

    
30
This module requires a minimum of Node v6.9.0 and Webpack v4.0.0, and must be used with a
31
server that accepts express-style middleware.
32

    
33
## Getting Started
34

    
35
First thing's first, install the module:
36

    
37
```console
38
npm install webpack-dev-middleware --save-dev
39
```
40

    
41
_Note: We do not recommend installing this module globally._
42

    
43
## Usage
44

    
45
```js
46
const webpack = require('webpack');
47
const middleware = require('webpack-dev-middleware');
48
const compiler = webpack({
49
  // webpack options
50
});
51
const express = require('express');
52
const app = express();
53

    
54
app.use(
55
  middleware(compiler, {
56
    // webpack-dev-middleware options
57
  })
58
);
59

    
60
app.listen(3000, () => console.log('Example app listening on port 3000!'));
61
```
62

    
63
## Options
64

    
65
The middleware accepts an `options` Object. The following is a property reference
66
for the Object.
67

    
68
_Note: The `publicPath` property is required, whereas all other options are optional_
69

    
70
### methods
71

    
72
Type: `Array`  
73
Default: `[ 'GET', 'HEAD' ]`
74

    
75
This property allows a user to pass the list of HTTP request methods accepted by the server.
76

    
77
### headers
78

    
79
Type: `Object`  
80
Default: `undefined`
81

    
82
This property allows a user to pass custom HTTP headers on each request. eg.
83
`{ "X-Custom-Header": "yes" }`
84

    
85
### index
86

    
87
Type: `String`  
88
Default: `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

    
96
Type: `Boolean`  
97
Default: `undefined`
98

    
99
This option instructs the module to operate in 'lazy' mode, meaning that it won't
100
recompile when files change, but rather on each request.
101

    
102
### logger
103

    
104
Type: `Object`  
105
Default: [`webpack-log`](https://github.com/webpack-contrib/webpack-log/blob/master/index.js)
106

    
107
In the rare event that a user would like to provide a custom logging interface,
108
this property allows the user to assign one. The module leverages
109
[`webpack-log`](https://github.com/webpack-contrib/webpack-log#readme)
110
for creating the [`loglevelnext`](https://github.com/shellscape/loglevelnext#readme)
111
logging management by default. Any custom logger must adhere to the same
112
exports for compatibility. Specifically, all custom loggers must have the
113
following exported methods at a minimum:
114

    
115
- `log.trace`
116
- `log.debug`
117
- `log.info`
118
- `log.warn`
119
- `log.error`
120

    
121
Please see the documentation for `loglevel` for more information.
122

    
123
### logLevel
124

    
125
Type: `String`  
126
Default: `'info'`
127

    
128
This property defines the level of messages that the module will log. Valid levels
129
include:
130

    
131
- `trace`
132
- `debug`
133
- `info`
134
- `warn`
135
- `error`
136
- `silent`
137

    
138
Setting a log level means that all other levels below it will be visible in the
139
console. Setting `logLevel: 'silent'` will hide all console output. The module
140
leverages [`webpack-log`](https://github.com/webpack-contrib/webpack-log#readme)
141
for logging management, and more information can be found on its page.
142

    
143
### logTime
144

    
145
Type: `Boolean`  
146
Default: `false`
147

    
148
If `true` the log output of the module will be prefixed by a timestamp in the
149
`HH:mm:ss` format.
150

    
151
### mimeTypes
152

    
153
Type: `Object`  
154
Default: `null`
155

    
156
This property allows a user to register custom mime types or extension mappings.
157
eg. `mimeTypes: { 'text/html': [ 'phtml' ] }`.
158

    
159
By default node-mime will throw an error if you try to map a type to an extension
160
that is already assigned to another type. Passing `force: true` will suppress this behavior
161
(overriding any previous mapping).
162
eg. `mimeTypes: { typeMap: { 'text/html': [ 'phtml' ] } }, force: true }`.
163

    
164
Please see the documentation for
165
[`node-mime`](https://github.com/broofa/node-mime#mimedefinetypemap-force--false) for more information.
166

    
167
### publicPath
168

    
169
Type: `String`  
170
_Required_
171

    
172
The 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

    
179
Type: `Object`  
180
Default: `undefined`
181

    
182
Allows users to provide a custom reporter to handle logging within the module.
183
Please see the [default reporter](/lib/reporter.js)
184
for an example.
185

    
186
### serverSideRender
187

    
188
Type: `Boolean`  
189
Default: `undefined`
190

    
191
Instructs the module to enable or disable the server-side rendering mode. Please
192
see [Server-Side Rendering](#server-side-rendering) for more information.
193

    
194
### stats
195

    
196
Type: `Object`  
197
Default: `{ context: process.cwd() }`
198

    
199
Options for formatting statistics displayed during and after compile. For more
200
information and property details, please see the
201
[webpack documentation](https://webpack.js.org/configuration/stats/#stats).
202

    
203
### watchOptions
204

    
205
Type: `Object`  
206
Default: `{ aggregateTimeout: 200 }`
207

    
208
The module accepts an `Object` containing options for file watching, which is
209
passed directly to the compiler provided. For more information on watch options
210
please see the [webpack documentation](https://webpack.js.org/configuration/watch/#watchoptions)
211

    
212
### writeToDisk
213

    
214
Type: `Boolean|Function`  
215
Default: `false`
216

    
217
If `true`, the option will instruct the module to write files to the configured
218
location on disk as specified in your `webpack` config file. _Setting
219
`writeToDisk: true` won't change the behavior of the `webpack-dev-middleware`,
220
and bundle files accessed through the browser will still be served from memory._
221
This option provides the same capabilities as the
222
[`WriteFilePlugin`](https://github.com/gajus/write-file-webpack-plugin/pulls).
223

    
224
This option also accepts a `Function` value, which can be used to filter which
225
files 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)
227
in which a return value of `false` _will not_ write the file, and a return value
228
of `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

    
240
Type: `Object`  
241
Default: `MemoryFileSystem`
242

    
243
Set 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
248
fs.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
254
interact with the middleware at runtime:
255

    
256
### `close(callback)`
257

    
258
Instructs a webpack-dev-middleware instance to stop watching for file changes.
259

    
260
### Parameters
261

    
262
#### callback
263

    
264
Type: `Function`
265

    
266
A function executed once the middleware has stopped watching.
267

    
268
### `invalidate()`
269

    
270
Instructs a webpack-dev-middleware instance to recompile the bundle.
271
e.g. after a change to the configuration.
272

    
273
```js
274
const webpack = require('webpack');
275
const compiler = webpack({ ... });
276
const middleware = require('webpack-dev-middleware');
277
const instance = middleware(compiler);
278

    
279
app.use(instance);
280

    
281
setTimeout(() => {
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

    
293
Executes a callback function when the compiler bundle is valid, typically after
294
compilation.
295

    
296
### Parameters
297

    
298
#### callback
299

    
300
Type: `Function`
301

    
302
A function executed when the bundle becomes valid. If the bundle is
303
valid at the time of calling, the callback is executed immediately.
304

    
305
```js
306
const webpack = require('webpack');
307
const compiler = webpack({ ... });
308
const middleware = require('webpack-dev-middleware');
309
const instance = middleware(compiler);
310

    
311
app.use(instance);
312

    
313
instance.waitUntilValid(() => {
314
  console.log('Package is in a valid state');
315
});
316
```
317

    
318
## Known Issues
319

    
320
### Multiple Successive Builds
321

    
322
Watching (by means of `lazy: false`) will frequently cause multiple compilations
323
as the bundle changes during compilation. This is due in part to cross-platform
324
differences in file watchers, so that webpack doesn't loose file changes when
325
watched files change rapidly. If you run into this situation, please make use of
326
the [`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

    
332
In 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
334
generated with each build.
335

    
336
With 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
338
developer 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
342
process is finished with server-side rendering enabled._
343

    
344
Example Implementation:
345

    
346
```js
347
const webpack = require('webpack');
348
const compiler = webpack({
349
  // webpack options
350
});
351
const isObject = require('is-object');
352
const middleware = require('webpack-dev-middleware');
353

    
354
// This function makes server rendering of asset references consistent with different webpack chunk/entry configurations
355
function normalizeAssets(assets) {
356
  if (isObject(assets)) {
357
    return Object.values(assets);
358
  }
359

    
360
  return Array.isArray(assets) ? assets : [assets];
361
}
362

    
363
app.use(middleware(compiler, { serverSideRender: true }));
364

    
365
// The following middleware would not be invoked until the latest build is finished.
366
app.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

    
398
We do our best to keep Issues in the repository focused on bugs, features, and
399
needed modifications to the code for the module. Because of that, we ask users
400
with general support, "how-to", or "why isn't this working" questions to try one
401
of the other support channels that are available.
402

    
403
Your 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
405
of those docs, please head over to the [webpack.js.org repo][wjo-url] and open a
406
pull request.
407

    
408
From there, we encourage users to visit the [webpack Gitter chat][chat-url] and
409
talk to the fine folks there. If your quest for answers comes up dry in chat,
410
head over to [StackOverflow][stack-url] and do a quick search or open a new
411
question. Remember; It's always much easier to answer questions that include your
412
`webpack.config.js` and relevant files!
413

    
414
If you're twitter-savvy you can tweet [#webpack][hash-url] with your question
415
and someone should be able to reach out and lend a hand.
416

    
417
If you have discovered a :bug:, have a feature suggestion, or would like to see
418
a modification, please feel free to create an issue on Github. _Note: The issue
419
template isn't optional, so please be sure not to remove it, and please fill it
420
out completely._
421

    
422
## Contributing
423

    
424
Please 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
(3-3/5)