• Stars
    star
    2,489
  • Rank 18,459 (Top 0.4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 12 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A development middleware for webpack

npm node tests coverage discussion size

webpack-dev-middleware

An express-style development middleware for use with webpack bundles and allows for serving of the files emitted from webpack. This should be used for development only.

Some of the benefits of using this middleware include:

  • No files are written to disk, rather it handles files in memory
  • If files changed in watch mode, the middleware delays requests until compiling has completed.
  • Supports hot module reload (HMR).

Getting Started

First thing's first, install the module:

npm install webpack-dev-middleware --save-dev

Warning

We do not recommend installing this module globally.

Usage

const webpack = require("webpack");
const middleware = require("webpack-dev-middleware");
const compiler = webpack({
  // webpack options
});
const express = require("express");
const app = express();

app.use(
  middleware(compiler, {
    // webpack-dev-middleware options
  })
);

app.listen(3000, () => console.log("Example app listening on port 3000!"));

See below for an example of use with fastify.

Options

Name Type Default Description
methods Array [ 'GET', 'HEAD' ] Allows to pass the list of HTTP request methods accepted by the middleware
headers Array|Object|Function undefined Allows to pass custom HTTP headers on each request.
index Boolean|String index.html If false (but not undefined), the server will not respond to requests to the root URL.
mimeTypes Object undefined Allows to register custom mime types or extension mappings.
mimeTypeDefault String undefined Allows to register a default mime type when we can't determine the content type.
publicPath String output.publicPath (from a configuration) The public path that the middleware is bound to.
stats Boolean|String|Object stats (from a configuration) Stats options object or preset name.
serverSideRender Boolean undefined Instructs the module to enable or disable the server-side rendering mode.
writeToDisk Boolean|Function false Instructs the module to write files to the configured location on disk as specified in your webpack configuration.
outputFileSystem Object memfs Set the default file system which will be used by webpack as primary destination of generated files.
modifyResponseData Function undefined Allows to set up a callback to change the response data.

The middleware accepts an options Object. The following is a property reference for the Object.

methods

Type: Array
Default: [ 'GET', 'HEAD' ]

This property allows a user to pass the list of HTTP request methods accepted by the middleware**.

headers

Type: Array|Object|Function Default: undefined

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

or

webpackDevMiddleware(compiler, {
  headers: () => {
    return {
      "Last-Modified": new Date(),
    };
  },
});

or

webpackDevMiddleware(compiler, {
  headers: (req, res, context) => {
    res.setHeader("Last-Modified", new Date());
  },
});

or

webpackDevMiddleware(compiler, {
  headers: [
    {
      key: "X-custom-header",
      value: "foo",
    },
    {
      key: "Y-custom-header",
      value: "bar",
    },
  ],
});

or

webpackDevMiddleware(compiler, {
  headers: () => [
    {
      key: "X-custom-header",
      value: "foo",
    },
    {
      key: "Y-custom-header",
      value: "bar",
    },
  ],
});

index

Type: Boolean|String Default: index.html

If false (but not undefined), the server will not respond to requests to the root URL.

mimeTypes

Type: Object
Default: undefined

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

Please see the documentation for mime-types for more information.

mimeTypeDefault

Type: String
Default: undefined

This property allows a user to register a default mime type when we can't determine the content type.

publicPath

Type: String Default: output.publicPath (from a configuration)

The public path that the middleware is bound to.

Best Practice: use the same publicPath defined in your webpack config. For more information about publicPath, please see the webpack documentation.

stats

Type: Boolean|String|Object Default: stats (from a configuration)

Stats options object or preset name.

serverSideRender

Type: Boolean
Default: undefined

Instructs the module to enable or disable the server-side rendering mode. Please see Server-Side Rendering for more information.

writeToDisk

Type: Boolean|Function
Default: false

If true, the option will instruct the module to write files to the configured location on disk as specified in your webpack config file. 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. This option provides the same capabilities as the WriteFilePlugin.

This option also accepts a Function value, which can be used to filter which files are written to disk. The function follows the same premise as 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.

const webpack = require("webpack");
const configuration = {
  /* Webpack configuration */
};
const compiler = webpack(configuration);

middleware(compiler, {
  writeToDisk: (filePath) => {
    return /superman\.css$/.test(filePath);
  },
});

outputFileSystem

Type: Object
Default: memfs

Set the default file system which will be used by webpack as primary destination of generated files. This option isn't affected by the writeToDisk option.

You have to provide .join() and mkdirp method to the outputFileSystem instance manually for compatibility with webpack@4.

This can be done simply by using path.join:

const webpack = require("webpack");
const path = require("path");
const myOutputFileSystem = require("my-fs");
const mkdirp = require("mkdirp");

myOutputFileSystem.join = path.join.bind(path); // no need to bind
myOutputFileSystem.mkdirp = mkdirp.bind(mkdirp); // no need to bind

const compiler = webpack({
  /* Webpack configuration */
});

middleware(compiler, { outputFileSystem: myOutputFileSystem });

modifyResponseData

Allows to set up a callback to change the response data.

const webpack = require("webpack");
const configuration = {
  /* Webpack configuration */
};
const compiler = webpack(configuration);

middleware(compiler, {
  // Note - if you send the `Range` header you will have `ReadStream`
  // Also `data` can be `string` or `Buffer`
  modifyResponseData: (req, res, data, byteLength) => {
    // Your logic
    // Don't use `res.end()` or `res.send()` here
    return { data, byteLength };
  },
});

API

webpack-dev-middleware also provides convenience methods that can be use to interact with the middleware at runtime:

close(callback)

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

Parameters

callback

Type: Function Required: No

A function executed once the middleware has stopped watching.

const express = require("express");
const webpack = require("webpack");
const compiler = webpack({
  /* Webpack configuration */
});
const middleware = require("webpack-dev-middleware");
const instance = middleware(compiler);

const app = new express();

app.use(instance);

setTimeout(() => {
  // Says `webpack` to stop watch changes
  instance.close();
}, 1000);

invalidate(callback)

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

Parameters

callback

Type: Function Required: No

A function executed once the middleware has invalidated.

const express = require("express");
const webpack = require("webpack");
const compiler = webpack({
  /* Webpack configuration */
});
const middleware = require("webpack-dev-middleware");
const instance = middleware(compiler);

const app = new express();

app.use(instance);

setTimeout(() => {
  // After a short delay the configuration is changed and a banner plugin is added to the config
  new webpack.BannerPlugin("A new banner").apply(compiler);

  // Recompile the bundle with the banner plugin:
  instance.invalidate();
}, 1000);

waitUntilValid(callback)

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

Parameters

callback

Type: Function Required: No

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

const express = require("express");
const webpack = require("webpack");
const compiler = webpack({
  /* Webpack configuration */
});
const middleware = require("webpack-dev-middleware");
const instance = middleware(compiler);

const app = new express();

app.use(instance);

instance.waitUntilValid(() => {
  console.log("Package is in a valid state");
});

getFilenameFromUrl(url)

Get filename from URL.

Parameters

url

Type: String Required: Yes

URL for the requested file.

const express = require("express");
const webpack = require("webpack");
const compiler = webpack({
  /* Webpack configuration */
});
const middleware = require("webpack-dev-middleware");
const instance = middleware(compiler);

const app = new express();

app.use(instance);

instance.waitUntilValid(() => {
  const filename = instance.getFilenameFromUrl("/bundle.js");

  console.log(`Filename is ${filename}`);
});

FAQ

Avoid blocking requests to non-webpack resources.

Since output.publicPath and output.filename/output.chunkFilename can be dynamic, it's not possible to know which files are webpack bundles (and they public paths) and which are not, so we can't avoid blocking requests.

But there is a solution to avoid it - mount the middleware to a non-root route, for example:

const webpack = require("webpack");
const middleware = require("webpack-dev-middleware");
const compiler = webpack({
  // webpack options
});
const express = require("express");
const app = express();

// Mounting the middleware to the non-root route allows avoids this.
// Note - check your public path, if you want to handle `/dist/`, you need to setup `output.publicPath` to `/` value.
app.use(
  "/dist/",
  middleware(compiler, {
    // webpack-dev-middleware options
  })
);

app.listen(3000, () => console.log("Example app listening on port 3000!"));

Server-Side Rendering

Note: this feature is experimental and may be removed or changed completely in the future.

In order to develop an app using server-side rendering, we need access to the stats, which is generated with each build.

With server-side rendering enabled, webpack-dev-middleware sets the stats to res.locals.webpack.devMiddleware.stats and the filesystem to res.locals.webpack.devMiddleware.outputFileSystem before invoking the next middleware, allowing a developer to render the page body and manage the response to clients.

Note: Requests for bundle files will still be handled by webpack-dev-middleware and all requests will be pending until the build process is finished with server-side rendering enabled.

Example Implementation:

const express = require("express");
const webpack = require("webpack");
const compiler = webpack({
  /* Webpack configuration */
});
const isObject = require("is-object");
const middleware = require("webpack-dev-middleware");

const app = new express();

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

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

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

// The following middleware would not be invoked until the latest build is finished.
app.use((req, res) => {
  const { devMiddleware } = res.locals.webpack;
  const outputFileSystem = devMiddleware.outputFileSystem;
  const jsonWebpackStats = devMiddleware.stats.toJson();
  const { assetsByChunkName, outputPath } = jsonWebpackStats;

  // Then use `assetsByChunkName` for server-side rendering
  // For example, if you have only one main chunk:
  res.send(`
<html>
  <head>
    <title>My App</title>
    <style>
    ${normalizeAssets(assetsByChunkName.main)
      .filter((path) => path.endsWith(".css"))
      .map((path) => outputFileSystem.readFileSync(path.join(outputPath, path)))
      .join("\n")}
    </style>
  </head>
  <body>
    <div id="root"></div>
    ${normalizeAssets(assetsByChunkName.main)
      .filter((path) => path.endsWith(".js"))
      .map((path) => `<script src="${path}"></script>`)
      .join("\n")}
  </body>
</html>
  `);
});

Support

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

Your first-stop-shop for support for webpack-dev-server should by the excellent documentation for the module. If you see an opportunity for improvement of those docs, please head over to the webpack.js.org repo and open a pull request.

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

If you're twitter-savvy you can tweet #webpack with your question and someone should be able to reach out and lend a hand.

If you have discovered a πŸ›, have a feature suggestion, or would like to see a modification, please feel free to create an issue on Github. Note: The issue template isn't optional, so please be sure not to remove it, and please fill it out completely.

Other servers

Examples of use with other servers will follow here.

Fastify

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.

const fastify = require("fastify")();
const webpack = require("webpack");
const webpackConfig = require("./webpack.config.js");
const devMiddleware = require("webpack-dev-middleware");

const compiler = webpack(webpackConfig);
const { publicPath } = webpackConfig.output;

(async () => {
  await fastify.register(require("fastify-express"));
  await fastify.use(devMiddleware(compiler, { publicPath }));
  await fastify.listen(3000);
})();

Contributing

Please take a moment to read our contributing guidelines if you haven't yet done so.

CONTRIBUTING

License

MIT

More Repositories

1

webpack

A bundler for javascript and friends. Packs many modules into a few bundled assets. Code Splitting allows for loading parts of the application on demand. Through "loaders", modules can be CommonJs, AMD, ES6 modules, CSS, Images, JSON, Coffeescript, LESS, ... and your custom stuff.
JavaScript
64,550
star
2

webpack-dev-server

Serves a webpack app. Updates the browser on changes. Documentation https://webpack.js.org/configuration/dev-server/.
JavaScript
7,796
star
3

tapable

Just a little module for plugins.
JavaScript
3,724
star
4

webpack-cli

Webpack's Command Line Interface
JavaScript
2,552
star
5

webpack.js.org

Repository for webpack documentation and more!
MDX
2,213
star
6

react-starter

[OUTDATED] Starter template for React with webpack. Doesn't focus on simplicity! NOT FOR BEGINNERS!
JavaScript
2,208
star
7

docs

[OLD] documentation for webpack
JavaScript
1,456
star
8

enhanced-resolve

Offers an async require.resolve function. It's highly configurable.
JavaScript
920
star
9

memory-fs

[DEPRECATED use memfs instead] A simple in-memory filesystem. Holds data in a javascript object.
JavaScript
882
star
10

analyse

analyse web app for webpack stats
JavaScript
879
star
11

webpack-pwa

Example for a super simple PWA with webpack.
JavaScript
809
star
12

loader-utils

utils for webpack loaders
JavaScript
765
star
13

react-webpack-server-side-example

Example of an react application with webpack including server-side rendering.
JavaScript
460
star
14

node-libs-browser

[DEPRECATED] The node core libs for in browser usage.
JavaScript
449
star
15

watchpack

Wrapper library for directory and file watching.
JavaScript
375
star
16

webpack-with-common-libs

webpack with some common libraries
JavaScript
340
star
17

loader-runner

Runs (webpack) loaders
JavaScript
299
star
18

webpack-sources

Source code handling classes for webpack
JavaScript
260
star
19

changelog-v5

Temporary repo for the changelog for webpack 5
253
star
20

schema-utils

Options Validation
JavaScript
241
star
21

meeting-notes

Webpack core team meeting notes.
188
star
22

concord

[WIP] concord modules specification
156
star
23

example-app

[OUTDATED] example web app for webpack
JavaScript
138
star
24

fastparse

A very simple and stupid parser, based on a statemachine and regular expressions.
JavaScript
65
star
25

enhanced-require

[CURRENTLY UNMAINTAINED] Enhance the require function in node.js with support for loaders which preprocess files. This is a standalone polyfill for features of webpack.
JavaScript
64
star
26

playground

In-browser playground for webpack
JavaScript
59
star
27

analyse-tool

A tool to analyse your webpack build result. It allows to browse the compilation and points out options to optimize the build.
JavaScript
55
star
28

hot-node-example

Example for HMR in a node.js process
JavaScript
54
star
29

source-list-map

Fast line to line SourceMap generator.
JavaScript
39
star
30

benchmark

Run benchmarks for webpack.
JavaScript
38
star
31

core

[OBSOLETE in webpack 2] The core of webpack and enhanced-require...
JavaScript
26
star
32

media

25
star
33

voting-app

An application for casting votes on new webpack features and fixes.
JavaScript
22
star
34

tooling

A collection of reusable tooling for webpack repos.
JavaScript
20
star
35

graph

[DEPRECATED] Converts JSON stats from webpack to a nice SVG-Image.
JavaScript
13
star
36

template

[DEPRECATED] Create a new web app from a template.
JavaScript
10
star
37

webpack.github.com

webpack.github.com
JavaScript
10
star
38

management

Mission, Goals, projects and budget for webpack
6
star
39

github-org-overview

Scans all repos of a github organization and check if published
JavaScript
5
star
40

the-big-test

[OUTDATED] the big webpack/enhanced-require test
JavaScript
5
star
41

meetup-2018-05-08

QA for the webpack meetup in Munich
4
star
42

v4.webpack.js.org

Hosting for old version of webpack documentation
3
star
43

jquery-wpt-module

[DEPRECATED] webpack-template-module for jquery
JavaScript
2
star
44

bootstrap-wpt-module

[DEPRECATED] webpack-template-module for twitter's bootstrap
JavaScript
2
star
45

github-wiki

The server-side code (heruko) for serving the wiki as gh-pages.
JavaScript
2
star
46

enhanced-resolve-completion-demo

[OUTDATED] demo for the request completion of enhanced-resolve
JavaScript
2
star
47

webpack-tests-example

DEPRECATED (use mocha-loader now): A simple example for doing tests with webpack and mocha.
JavaScript
2
star