Giter Site home page Giter Site logo

webpack-dev-middleware's Introduction

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.
etag boolean| "weak"| "strong" undefined Enable or disable etag generation.
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.

etag

Type: "weak" | "strong"
Default: undefined

Enable or disable etag generation. Boolean value use

lastModified

Type: Boolean Default: undefined

Enable or disable Last-Modified header. Uses the file system's last modified value.

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 discussions 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.

Connect

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

const compiler = webpack(webpackConfig);
const devMiddlewareOptions = {
  /** Your webpack-dev-middleware-options */
};
const app = connect();

app.use(devMiddleware(compiler, devMiddlewareOptions));

http.createServer(app).listen(3000);

Express

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

const compiler = webpack(webpackConfig);
const devMiddlewareOptions = {
  /** Your webpack-dev-middleware-options */
};
const app = express();

app.use(devMiddleware(compiler, devMiddlewareOptions));

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

Koa

const Koa = require("koa");
const webpack = require("webpack");
const webpackConfig = require("./test/fixtures/webpack.simple.config");
const middleware = require("./dist");

const compiler = webpack(webpackConfig);
const devMiddlewareOptions = {
  /** Your webpack-dev-middleware-options */
};
const app = new Koa();

app.use(middleware.koaWrapper(compiler, devMiddlewareOptions));

app.listen(3000);

Hapi

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

const compiler = webpack(webpackConfig);
const devMiddlewareOptions = {};

(async () => {
  const server = Hapi.server({ port: 3000, host: "localhost" });

  await server.register({
    plugin: devMiddleware.hapiPlugin(),
    options: {
      // The `compiler` option is required
      compiler,
      ...devMiddlewareOptions,
    },
  });

  await server.start();

  console.log("Server running on %s", server.info.uri);
})();

process.on("unhandledRejection", (err) => {
  console.log(err);
  process.exit(1);
});

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 devMiddlewareOptions = {
  /** Your webpack-dev-middleware-options */
};

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

Contributing

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

CONTRIBUTING

License

MIT

webpack-dev-middleware's People

Contributors

alexander-akait avatar alexhancock avatar anshumanv avatar clshortfuse avatar danez avatar dependabot[bot] avatar dmohns avatar evilebottnawi avatar ferdinando-ferreira avatar gpoitch avatar grawk avatar hiroppy avatar hzoo avatar ijse avatar iyuq avatar jamesgeorge007 avatar jhnns avatar knagaitsev avatar michael-ciniawsky avatar nuintun avatar piperchester avatar rdrey avatar renovate[bot] avatar runrioter avatar shellscape avatar simenbrekken avatar snitin315 avatar sokra avatar spacek33z avatar wuct avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

webpack-dev-middleware's Issues

Not working on mac

I am not sure whether the problem is caused from webpack-dev-middleware

here are the broken codes:

let compiler = webpack(config);
_rootExpressApp.use(webpackDevMiddleware(compiler, {
  noInfo: true,
  publicPath: config.output.publicPath,
}));
_rootExpressApp.use(webpackHotMiddleware(compiler));

the codes are modified from react-transform-boilerplate

my project worked properly on windows but got 404 error when I request the bundle.js on mac

why the middleware was just passed through and didn't send back any scripts on mac?

Options to exclude files

Hey @sokra!

I just had some troubles on osx and the max. file watcher limit.
Is it possible to exclude certain folders via options?

Excluding node_modules would probably solve my problems.

Spinning within docker?

Hi, I was just wondering if I could get some insight into this module. I'm using this in a project running a Node server, but have been porting to use Docker. In Docker, I start bash and start running the Node server as I typically do, but the Webpack watcher perpetually spins. It creates itself and then automatically invalidates itself and rebuilds.

Could you offer any insight into what would cause the middleware to spin?

Warnings and Errors only

How can I use this middleware and only get logging information about errors and warnings only, not full stats?

How to handle changes in backend files (eg. a route file in Express)?

Hello, I'm getting started with Express + Webpack but I'm having a hard to time figuring out what is the best setup to use.

At the moment I am using Weback to bundle all the "frontend" files (i.e. used by the client/browser), so if I change something regarding the client, webpack-dev-middleware works perfectly and it updates the bundle in memory in a fraction of a second.
But if something is changed eg. in a route file, nothing changes and I have to restart the server to see the updates, this implies that webpack-dev-middleware has to create the bundle from scratch and it takes (at the moment) ~6secs. During development, waiting for such time for every changes I make is a bit annoying.

Is there a smarter way of working with this setup? Hope someone can share his experience.
Thanks!

Doesn't reload the browser after re-compiling

I'm not sure it's a bug but I'm trying to switch from watch-build cycle to using of connect + middleware. The only problem is that after recompiling the bundle browser doesn't reload it. If I do manual refresh I can see an updated bundle. Please advise where I can look for it.

Conflict with html-webpack-plugin on catch all route

I have a single page app and I am using the middleware during dev. I want to route all requests in express to the index.html file so that my spa router takes over. There seems to be a problem with webpack-dev-middleware trying to detect the file or path, which prevents me from rendering the index.html file with the html-webpack-plugin.

Here is essentially what I have:

// webpack.config
    new HtmlWebpackPlugin({
      template : paths.src('index.html'),
      hash     : true,
      filename : 'index.html',
      inject   : 'body'
    })

// server.js
const devMiddleware = WebpackDevMiddleware(compiler, {
  publicPath: webpackConfig.output.publicPath,
  contentBase: paths.project(config.get('dir_src')),
  hot: true,
  quiet: true,
  noInfo: false,
  lazy: false,
  stats: {
    colors: true
  },
  historyApiFallback: true
});
app.use(devMiddleware);

app.use((req, res, next) => {
  console.log('Final Request', req.url, req.method, req.accepts('html'));
  if (req.method === 'GET' && req.accepts('html')) {
    //res.sendFile(paths.src('index.html'), err => err && next());
    res.write(devMiddleware.fileSystem.readFileSync(paths.src('index.html')));
    res.send();
    next();
  } else next();
});

This results in the following error:

Error: no such file or directory
   at MemoryFileSystem.readFileSync (node_modules/webpack-dev-middleware/node_modules/memory-fs/lib/MemoryFileSystem.js:107:10)
   at build/webpack-dev-server.js:74:40
   at Layer.handle [as handle_request] (node_modules/express/lib/router/layer.js:95:5)
   at trim_prefix (node_modules/express/lib/router/index.js:312:13)
   at node_modules/express/lib/router/index.js:280:7
   at Function.process_params (node_modules/express/lib/router/index.js:330:12)
   at next (node_modules/express/lib/router/index.js:271:10)
   at middleware (node_modules/webpack-hot-middleware/middleware.js:32:48)
   at Layer.handle [as handle_request] (node_modules/express/lib/router/layer.js:95:5)
   at trim_prefix (node_modules/express/lib/router/index.js:312:13)
   at node_modules/express/lib/router/index.js:280:7
   at Function.process_params (node_modules/express/lib/router/index.js:330:12)
   at next (node_modules/express/lib/router/index.js:271:10)
   at node_modules/webpack-dev-middleware/middleware.js:166:12
   at continueBecauseBundleAvailible (node_modules/webpack-dev-middleware/middleware.js:58:5)
   at Array.forEach (native)

I confirmed the path is correct and could be read with: fs.readFileSync(paths.src('index.html')). However it appears the upstream library may have an issue.

webpack 2, ids collision

have many entry points.

        "vendor": ["lodash", "backbone", .... ],
        "common": ["common/module1", "common/module2"..." ],
        "page1": "page1",
        "page2": "page2",

...
     new CommonsChunkPlugin({
            // The order of this array matters
            names: [ "rest", "common", "vendor" ],
            minChunks: 3
        }),

Same Id assigned to modules in different chunks.
Have not good and small reproduce( our project have >1000 modules )
Probably its because each chunk loaded independently and at same time?

Production bundles via "webpack" generated fine.

webpack-dev问题

Dev的時候可以跑 api server + webpack-dev-server(hot load)
Production的時候可以跑 api server + webpack build
有什么解决方案?

Higher CPU load than webpack-dev-server?

I was playing around with making my own asset server (to replace webpack-dev-server) and noticed that it causes a huge spike in CPU load (~100% with fans spinning) compared to the dev server (~3%) when both are just idling.

These are just measured using Activity Monitor on a 10.9.5 Macbook Pro (quad core i7, 16GB RAM). Don't think the specs of the machine are super relevant, but there's definitely a noticeable difference when switching between the two and wanted to see if anyone had input.

Quiet and noInfo options not suppressing logs in browser

Hi,

I'm using the API and setting quiet and noInfo to true as follows:

  new WebpackDevServer(webpack(webpackConfig.client), {
    publicPath: webpackConfig.client.output.publicPath,
    hot: true,
    quiet: true,
    noInfo: true
  }).listen(4000, 'localhost', function (err, result) {
    if(err) {
      console.log('error', err);
    }
    else {
      console.log('info', "dev server listening on 4000");
    }
  });

When I run the server node devServer.js I simply get the dev server listening on 4000 message and no other output which is what I want.

When I visit my app in the browser though, which includes the following:

<script src="http://localhost:4000/bundle/client.js"></script>

My browser's console is spammed with socket logs. Is this expected? Shouldn't the quiet option prevent this?

`lazy: true` won't ever trigger rebuild without undocumented option "filename" set.

I have it narrowed down to line 135 of middleware.js:

if(options.lazy && filename === pathJoin(compiler.outputPath, options.filename))

When the undocumented option filename isn't set, it will attempt to match /Users/tom/Documents/somewebsite/dist/undefined, fail, and the request will fall through to the next handler, regardless of the file.

Setting { lazy: true, filename: "client.js" } in the dev-middleware config allows it to handle the request, but this won't work for webpack configurations with multiple entry points.

Hot reload fails to download patch when public path is specified

Trying to proxy server and mount js file in expected dev build location in webpack-dev-server grunt config to intercept requests for http://localhost:6001/slm/js/alm/builds/components/alm-components.js
...
publicPath: '/slm/js/alm/builds/components'

This works now but hot reloading is no longer able to find the update chunks at /af64be6a5c4098fd56ce.hot-update.json

but works if public path is specified:
curl http://localhost:6001/slm/js/alm/builds/components/af64be6a5c4098fd56ce.hot-update.json
{"h":"1da04cff58307a4c0143","c":[0]}

It seems that it still needs to expect update chunks to be at root or hot reload module needs to know the public path.

Does it support proxy config like webpack-dev-server?

`var express = require('express')
var webpack = require('webpack')

var app = express()
var compiler = webpack(config)

// handle fallback for HTML5 history API
app.use(require('connect-history-api-fallback')())

// serve webpack bundle output
app.use(require('webpack-dev-middleware')(compiler, {
publicPath: config.output.publicPath,
proxy: {
'/xxx*': {
target: 'http://1.2.3.4:8080/aaa'
}
},
stats: {
colors: true,
chunks: false
}
}))`

I tried this but it seems not working for proxy

How to use this module with HapiJS ecosystem?

Can you provide an example of how to use this plugin with HapiJS ecosystem?

Below is the configuration i used with Hapi. Thats all i have configured. When i open my server @ localhost:3000 i got an error as below screen shot

webpack-dev-middleware

'use strict';

/* global __dirname */

const Webpack = require('webpack');
const Path = require('path');

module.exports = {
  'devtool': 'eval',
  'entry': [
    'webpack-hot-middleware/client?path=/__webpack_hmr&reload=true',
    './app/main.js'
  ],
  'output':{
    'path': __dirname + '/public/',
    'filename' : 'bundle.js',
    'publicPath' : '/'
  },
  'plugins':[
    new Webpack.optimize.OccurenceOrderPlugin(),
    new Webpack.HotModuleReplacementPlugin(),
    new Webpack.NoErrorsPlugin()
  ],
  'module': {
    'loaders':[
      {
        'test': /\.js$/,
        'include': Path.join(__dirname, 'app'),
        'loader': 'babel-loader'
      }
    ]
  }
};

compiler.plugin is not a function

I'm following the Browsersync - Webpack + React Hot Loader / React Transform HMR recipes trying to add hot-loader into my Gulp build system, but, I'm seeing the following error and I'm not sure to understand how this works in order to determine if this is an issue.

[19:41:07] TypeError: compiler.plugin is not a function
    at module.exports (Z:\development\reactjs\node_modules\webpack-dev-middleware\middleware.js:35:11)
    at Gulp.<anonymous> (Z:\development\reactjs\gulpfile.js:271:17)
    at module.exports (Z:\development\reactjs\node_modules\orchestrator\lib\runTask.js:34:7)
    at Gulp.Orchestrator._runTask (Z:\development\reactjs\node_modules\orchestrator\index.js:273:3)
    at Gulp.Orchestrator._runStep (Z:\development\reactjs\node_modules\orchestrator\index.js:214:10)
    at Gulp.Orchestrator.start (Z:\development\reactjs\node_modules\orchestrator\index.js:134:8)
    at C:\Users\geedmo\AppData\Roaming\npm\node_modules\gulp\bin\gulp.js:129:20
    at doNTCallback0 (node.js:419:9)
    at process._tickCallback (node.js:348:13)
    at Function.Module.runMain (module.js:469:11)

Any thoughts?

what is the endpoint?

assuming a configuration like this:

var express = require('express');
var webpack = require('webpack');
var webpackMiddleware = require('webpack-dev-middleware');

var app = express();

app.use(webpackMiddleware(webpack({
  entry: "mocha!./test/all.js",
  output: {
    path: "/"
  }
})));

app.listen(8000);

Where all.js contains some mocha tests... what is the resulting endpoint to view them? http://localhost:8000/bundle.js shows me the bundle, but I don't know how to get to the test suite runner html?

Option for compact console info

Hello!
It would be greate, if was an option for compact info in console instead of full list of all depeneds in bundle.
It needs for knowing when bundle compiled after change without watching full deps list

hot reload fails when using Webstorm 2016.1

I found that hot reload stopped working when I upgraded Webstorm as below, so copying in here from https://youtrack.jetbrains.com/issue/WEB-21174 in case it helps anyone:

I have this issue as well, I updated from 11.0.3 to 2016.1 and hot reload is broken. Unselecting the "safe write" option resolves the issue. (Appearance and behaviour > System Settings > Synchronization) Hot reload was working fine in 11.0.3 without changing this option, so I think this is something for you to address.

Issue on updating to 1.5.0

Getting an issue from 1.4.1 to 1.5.0 and seems to be from https://github.com/webpack/webpack-dev-middleware/pull/27/files but not sure if it's a package issue or on my side.

TypeError: res.send is not a function
    at processRequest (/app/node_modules/webpack-dev-middleware/middleware.js:189:8)
    at ready (/app/node_modules/webpack-dev-middleware/middleware.js:96:20)
    at webpackDevMiddleware (/app/node_modules/webpack-dev-middleware/middleware.js:162:3)

I get the following issue on "npm start"

/home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/webpack-dev-middleware/middleware.js:104
            if(err) throw err;
                    ^
Error: invalid argument
    at pathToArray (/home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/memory-fs/lib/MemoryFileSystem.js:44:10)
    at MemoryFileSystem.mkdirpSync (/home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/memory-fs/lib/MemoryFileSystem.js:139:13)
    at MemoryFileSystem.(anonymous function) [as mkdirp] (/home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/memory-fs/lib/MemoryFileSystem.js:279:34)
    at Compiler.<anonymous> (/home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/webpack/lib/Compiler.js:229:25)
    at Compiler.applyPluginsAsync (/home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/tapable/lib/Tapable.js:61:69)
    at Compiler.emitAssets (/home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/webpack/lib/Compiler.js:226:7)
    at Watching.<anonymous> (/home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/webpack/lib/Compiler.js:54:18)
    at /home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/webpack/lib/Compiler.js:403:12
    at Compiler.next (/home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/tapable/lib/Tapable.js:68:11)
    at Compiler.<anonymous> (/home/aftab/My_Files/Learning/Programming/Web_Dev/React/TypeIt/client/node_modules/webpack/lib/CachePlugin.js:40:4)

This is my configuration file

import express from 'express';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import webpackConfigBuilder from '../webpack.config';

const webpackConfig = webpackConfigBuilder('development');
const config = webpack(webpackConfig);

let app = express();

const compiler = webpack(config);
const middleware = webpackDevMiddleware(compiler, {
  publicPath: config.output.publicPath,
  contentBase: 'src',
  stats: {
    colors: true,
    hash: false,
    timings: true,
    chunks: false,
    chunkModules: false,
    modules: false
  }
});

app.use(middleware);
app.use(webpackHotMiddleware(compiler));
app.get('/test', function response(req, res) {
  res.write(middleware.fileSystem.readFileSync(__dirname+"/../dist/index.html"));
  res.end();
});

app.listen(8089, function onStart(err) {
  if(err) {
    console.log(err);
  }
  console.info("Listening on 8089, open in browser");
});

Where am I going wrong?

devMiddleware.fileSystem.readFileSync not work with gulp

Hi, @sokra , I'm getting started with webpack-dev-middleware and Gulp, but I have trouble with webpack-dev-middleware. In development mode, when I start the server by npm start, it's normal. However, I use Gulp task to start the server, an error happened:

Error: no such file or directory
   at MemoryFileSystem.readFileSync (d:\sources\modern-java-web-scaffold\frontend\node_modules\memory-fs\lib\MemoryFileSystem.js:114:10)
   at d:\sources\modern-java-web-scaffold\frontend\gulpfile.js:80:44
   at Layer.handle [as handle_request] (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\layer.js:95:5)
   at next (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\route.js:131:13)
   at Route.dispatch (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\route.js:112:3)
   at Layer.handle [as handle_request] (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\layer.js:95:5)
   at d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\index.js:277:22
   at param (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\index.js:349:14)
   at param (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\index.js:365:14)
   at Function.process_params (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\index.js:410:3)
   at next (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\index.js:271:10)
   at favicon (d:\sources\modern-java-web-scaffold\frontend\node_modules\serve-favicon\index.js:72:7)
   at Layer.handle [as handle_request] (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\layer.js:95:5)
   at trim_prefix (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\index.js:312:13)
   at d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\index.js:280:7
   at Function.process_params (d:\sources\modern-java-web-scaffold\frontend\node_modules\express\lib\router\index.js:330:12)

The main code in gulpfile.js as following:

gulp.task('dev-server', ['build-dev'], () => {
    const compiler = webpack(devConfig);
    const devMiddleware = webpackDevMiddleware(compiler, {
        publicPath: devConfig.output.publicPath,
        contentBase: 'src',
        stats: {
            colors: true,
            hash: false,
            timings: true,
            chunks: false,
            chunkModules: false,
            modules: false
        }
    });

    app.use(devMiddleware);
    app.use(webpackHotMiddleware(compiler));
    configFavicon(app);
    app.get('*', (req, res) => {
        res.write(devMiddleware.fileSystem.readFileSync(path.join(__dirname, 'dist/index.html')));
        res.end();
    });

    app.listen(port, '0.0.0.0', err => {
            if (err) throw new gutil.PluginError('dev-server', err);
            gutil.log('[dev-server]', '==> Listening on port ' + port + '. Open up http://0.0.0.0:' + port + '/ in your browser.');
    });
});

And this is my project's address: modern-java-web-scaffold. Is there something wrong with me? Could you give me some advice or solutions.
Thanks in advance.

Support History API urls

Hey there,

I am using webpack-dev-middleware to develop a SPA, with an index.html which is programatically generated by webpack. With this plugin, if I navigate to anything other than / or /index.html, the middleware does not pick up the request, and the request fails.

For most people, something like this solves the problem:

app.get('*', function (req, res) {
  res.send(path.join(__dirname, 'index.html'))
}

but for previously mentioned reasons, this doesn't work. I have written this handler to catch urls missed by webpack-dev-middleware, but would look at adding this into the core.

app.use(function (req, res, next) {
  if (req.url.match(/^(\/[a-zA-Z-]+)+(.html)?(\?.+)?$/)) { // Just a regex I spun up to sort my use case
    devMiddleware(
      {
        url: '/index.html'
      },
      res,
      next
    )
  } else {
    next()
  }
})

Forgive me if I've completely missed a config flag or something - I have looked at the source and couldn't find anything.

I am happy to help write a PR to support this, especially since this will become more popular with react-transform becoming more popular.

Thanks for your help in advance

Hot module replacement support?

I'm trying to enable hot module replacement support, but webpack-dev-middleware doen't seem to be capturing requests for /socket.io/1/?t=1423..., which end up falling through to regular page routing.

In my Gruntfile.js (it's the very first middleware):

middlewares.unshift(webpackMiddleware(
  webpack(webpackConfig(['client', 'dev'])), {
    hot: true,
    noInfo: true,
    stats: { color: true }
  }));

Relevant parts of webpack.config.js:

    entry: {
      client: [
        'webpack-dev-server/client?http://localhost:9001',
        'webpack/hot/only-dev-server',
        'client.jsx'
      ]
    },
    plugins: [
      new webpack.DefinePlugin({
        'process.env': {
          'NODE_ENV': JSON.stringify('development')
        }
      }),
      new webpack.HotModuleReplacementPlugin()
    ]

Is this possible to do within the middleware only?

Issue when making concurrent requests

There seems to be an issue when making multiple concurrent requests to webpack-dev-middleware simultaneously. I am using the following config:

{
        lazy:true, 
        publicPath:'/build/',
        filename: "commons.js",
        noInfo: false
}

I have webpack middleware included as part of my dev server which also includes tinyLr for automatic reloading. I am not using the full webpack dev server because I also have my dev server configured to mock my server-side. This all works fine if I have one browser open, but if I have two browsers open to my site at the same time, the server crashes as soon as both browsers try to reload at once. I get the below error message:

/Users/sam/Dropbox/Development/Projects/Apple/reviz/node_modules/webpack/node_modules/tapable/lib/Tapable.js:71
        plugins[this._currentPluginApply].apply(this, args);
                                          ^
TypeError: Cannot call method 'apply' of undefined
    at Tapable.next (/Users/sam/Dropbox/Development/Projects/Apple/reviz/node_modules/webpack/node_modules/tapable/lib/Tapable.js:71:37)
    at done (/Users/sam/Dropbox/Development/Projects/Apple/reviz/node_modules/webpack/node_modules/async/lib/async.js:135:19)
    at /Users/sam/Dropbox/Development/Projects/Apple/reviz/node_modules/webpack/node_modules/async/lib/async.js:32:16
    at /Users/sam/Dropbox/Development/Projects/Apple/reviz/node_modules/webpack/lib/CachePlugin.js:33:6
    at Storage.finished (/Users/sam/Dropbox/Development/Projects/Apple/reviz/node_modules/webpack/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js:38:16)
    at Object.oncomplete (evalmachine.<anonymous>:107:15)

Outdated version on NPM ?

Hi,

it looks like the version installed via NPM is not the same as the one visible here in the repo.
Especially, the waitUntilValid function is not referenced anywhere.

Any clue about that ?
Thank you.

[HMR] Update check failed: SyntaxError: Unexpected token <

I'm having an issue with hot module reloading on this repo.

I receive the following error:

[HMR] Update check failed: SyntaxError: Unexpected token <
  at Object.parse (native)
  at XMLHttpRequest.request.onreadystatechange (http://localhost:3000/js/client.js:44:33)

The error comes from within hotDownloadManifest. The request.responseText is HTML, rather than the usual json. This gets passed into JSON.parse which throws. I cannot work out why responseText is HTML.

This repo has a fair amount of CSS split into different files. If I remove a few on the CSS imports it works (most of the time), so my best guess is that it's something to do with a file limit. Could this be the case?

Access memoryfs files

Hi, so I know that this middleware automatically handles the serving of all assets from memory. However, is there a way to let express use this memoryFs for other middleware as well? So that I can, for example, use res.render('myfile.ext') where myfile.ext is also in the webpack-dev memoryFs?

'alias' default lookup directories

Hey @sokra

I'm trying to replace net with net-chromeify

I've put net-chromeify in ./web_modules/ and this works fine on the command-line: webpack src/ComponentLoader.js temp.js --alias net=net-chromeify

I'm trying to do the same thing with webpack-dev-middleware. My config in main.js is this:

app.use(require('webpack-dev-middleware')(__dirname, "./src/ComponentLoader", {
  webpack: {
    watch: true,
    debug: true,
    publicPrefix: "http://localhost:3000/scripts/",
    output: "bundle.js",
    libary: "ComponentLoader",
    alias: {net: "net-chromeify"} //I've also tried moving it outside the webpack hash
  }
})); 

but it can't seem to find net-chromeify. The error suggests that it's looking for net and not net-chromeify:

ERROR: Cannot find module 'net'
Error: Module "net" not found in context "/Users/rainerdreyer/Workspace/PipeDream/components"
Error: /Users/rainerdreyer/Workspace/PipeDream/node_modules/webpack-dev-middleware/node_modules/webpack/buildin/net is not a directory
@ /Users/rainerdreyer/Workspace/PipeDream/components/ServerEndpoint.js (line 2, column 8)

net is not a directory...

Why is it looking for net and not net-chromeify?

Thanks! :)

Auto-reloading files on Windows not working without webpack-hot-middleware

Hi, it seems that the auto-reload (not hot module replacement, just the refreshing of files over websockets) feature of webpack-dev-middleware does not appear to be working on Windows at the moment.

I think it may be a similar issue to what was previously reported with webpack-dev-server: webpack/webpack-dev-server#155

I set the middleware to log out to the console, and I can see that it's getting rebuilt every time on file saves, but it just doesn't communicate back to the browser without a manual page refresh.

What's strange is everything appears to work as it should when including webpack-hot-middleware along with it. However, a lot of people are starting to remove webpack-hot-middleware from their projects for a few different reasons:

  1. The future of how hot reloading will be accomplished (at least in React) seems to still be up in the air... Some are wanting to back out of it for now until new methods are established,
  2. Hot reloading does not currently work with purely functional React components, and many are choosing to go this route now with libraries like recompose out there to help make it more easily achievable.

Ideally, we should be able to at least take advantage of the auto-reload feature without the use of webpack-hot-middleware, but I can't pinpoint what's causing it to break at the moment. Anyone have any ideas?

two babel config issue

Hi

I have a server which is using babel-register and .babelrc. It is working fine.
The problem is with this library or webpack library. I am trying to use a different settings for the babel but without any success. WebpackDevMiddleware will always use config from the .babelrc loaded by babel-register. I am not sure maybe it is not possible to set a different babel config with babel-register.

Here is a small example

const differentBabelConfig = {
  // other babel config different form .babelrc
};

const compiler = new webpack({
// ...
{ test: /\.(js|jsx)$/, exclude: /node_modules\/(?!cherry)/, loader: 'babel-loader', query: differentBabelConfig },
// ... 
})

Thank you for any help with it

Invalid argument

I am getting the following error trying to build my bundle. Can anyone help?

Error: invalid argument
    at pathToArray (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack-dev-middleware/node_modules/memory-fs/lib/MemoryFileSystem.js:44:10)
    at MemoryFileSystem.mkdirpSync (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack-dev-middleware/node_modules/memory-fs/lib/MemoryFileSystem.js:139:13)
    at MemoryFileSystem.(anonymous function) [as mkdirp] (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack-dev-middleware/node_modules/memory-fs/lib/MemoryFileSystem.js:279:34)
    at Compiler.<anonymous> (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/lib/Compiler.js:229:25)
    at Compiler.applyPluginsAsync (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/node_modules/tapable/lib/Tapable.js:60:69)
    at Compiler.emitAssets (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/lib/Compiler.js:226:7)
    at Watching.<anonymous> (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/lib/Compiler.js:54:18)
    at /Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/lib/Compiler.js:403:12
    at Compiler.next (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/node_modules/tapable/lib/Tapable.js:67:11)
    at Compiler.<anonymous> (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/lib/CachePlugin.js:40:4)
    at Compiler.applyPluginsAsync (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/node_modules/tapable/lib/Tapable.js:71:13)
    at Compiler.<anonymous> (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/lib/Compiler.js:400:9)
    at Compilation.<anonymous> (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/lib/Compilation.js:577:13)
    at Compilation.applyPluginsAsync (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/node_modules/tapable/lib/Tapable.js:60:69)
    at Compilation.<anonymous> (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/lib/Compilation.js:572:10)
    at Compilation.applyPluginsAsync (/Users/chrisdziewa/Web Portfolio/Dynamic Web Apps/voting-app/node_modules/webpack/node_modules/tapable/lib/Tapable.js:60:69)

Emitting event to window

Hey, I'm wondering if we can see when there is a module update from within the app. This would allow us to 'refresh' the page within a SPA to get the latest changes. I'm imagining some event that we can watch from the window object.

Does this work with hot loading?

I see WebpackDevServer comes with special support for hot loading. Middleware does not seem to include it. Is it possible to use the middleware with hot loading somehow?

Invalid argument in watchOptions

I'm getting this error

D:\my-path\node_modules\webpack-dev-middleware\middleware.js:107
                        if(err) throw err;
                                ^
 Error: invalid argument
    at pathToArray (D:\my-path\node_modules\memory-fs\lib\MemoryFileSystem.js:44:10)
    at MemoryFileSystem.mkdirpSync (D:\my-path\node_modules\memory-fs\lib\MemoryFileSystem.js:139:13)
    at MemoryFileSystem.(anonymous function) [as mkdirp] (D:\my-path\node_modules\memory-fs\lib\MemoryFileSystem.js:279:34)
    at Compiler.<anonymous> (D:\my-path\node_modules\webpack\lib\Compiler.js:229:25)
    at Compiler.applyPluginsAsync (D:\my-path\node_modules\tapable\lib\Tapable.js:60:69)
    at Compiler.emitAssets (D:\my-path\node_modules\webpack\lib\Compiler.js:226:7)
    at Watching.<anonymous> (D:\my-path\node_modules\webpack\lib\Compiler.js:54:18)
    at D:\my-path\node_modules\webpack\lib\Compiler.js:403:12
    at Compiler.next (D:\my-path\node_modules\tapable\lib\Tapable.js:67:11)
    at Compiler.<anonymous> (D:\my-path\node_modules\webpack\lib\CachePlugin.js:40:4)

This is the code that throws an error:

    if(!options.lazy) {
        var watching = compiler.watch(options.watchOptions, function(err) {
            if(err) throw err;
        });
    } else {
        state = true;
    }

Error object:

{ [Error: invalid argument]
  code: 'EINVAL',
  errno: 18,
  message: 'invalid argument',
  path: 'build\\js' }

Watch options I'm passing:

watchOptions: {
        aggregateTimeout: 100
    }

if there is lazy : true option - everything works fine

Giving access to files outside of contentBase:...

after a great start:
yo react-webpack
yo react-webpack:component foo
grunt serve...

How do I allow access to the node_modules or bower_components directory in the index.html file?

My current solution was to use a grunt task to copy the files from the ./node_modules/... directory to the src/styles/vendor/... directory.
...
copy: {
dev: {
files: [
{
src: [__dirname + '/node_modules/bootstrap/dist/css/bootstrap.min.css' ],
dest: '<%= pkg.src %>/styles/vendor/bootstrap.min.css'
}
]
},
...

For development purposes I would rather have something like:

...index.html
<link href="/node_modules/bootstrap/dist/css/bootstrap.min.css" media="all" rel="stylesheet" />

Not recompiling after file changes

I'm using webpack-dev-middleware on my express app. Everything looks as expected when I start my app. When I'm making changes as its running, I'm not seeing assets recompile. The documentation gives the impression that it's in watch mode by default and "the compiler recompiles on file changes". Is there something obvious I'm missing? Are there other examples that use webpack-dev-middleware? (other than webpack-dev-server).

Any help is appreciated.

Setup

var webpack = require("webpack");
var webpackDevMiddleware = require("webpack-dev-middleware");
var webpackConfig = require('../webpack.config');
var compiler = webpack(webpackConfig);

app.use(webpackDevMiddleware(compiler));

Config (Note: publicPath is temporarily set to the dev publicPath).

var webpack = require('webpack');
var path = require('path');
var ExtractTextPlugin = require('extract-text-webpack-plugin');

module.exports = {

    entry: {
        lib: ['react', 'react-router'],
        main: './app/client.js'
    },

    output: {
        path: __dirname + '/public',
        filename: '/bundle.js',
        publicPath: 'http://localhost:3000'
    },

    resolve: {
        extensions: ['', '.js', '.jsx', '.scss'],
        moduleDirectories: ['node_modules', 'bower_components']
    },

    module: {
        loaders: [
            { test: /\.(js|jsx)$/, loader: 'jsx-loader' },
            { test: /\.scss$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader!sass-loader') },
            { test: /\.css$/, loader: ExtractTextPlugin.extract('style-loader', 'css-loader') },
            { test: /\.(png|jpg)$/, loader: 'file-loader' }
        ]
    },

    plugins: [
        new ExtractTextPlugin('global.css')
    ]
};

Node 6 Compile issues

After updating to Node 6 I am now getting the following issues:

(node) v8::ObjectTemplate::Set() with non-primitive values is deprecated
(node) and will stop working in the next major release.

==== JS stack trace =========================================

Security context: 0x641b9ec9fa9 <JS Object>#0#
    1: .node [module.js:568] [pc=0x31a5c5dec944] (this=0x766c05fe979 <an Object with map 0x34b7d5a90559>#1#,module=0x12cc82d850e1 <a Module with map 0x34b7d5a181b9>#2#,filename=0x12cc82d850a9 <String[118]: /Users/tal.woolf/developer/frontend/docker-test/node_modules/fsevents/lib/binding/Release/node-v48-darwin-x64/fse.node>)
    2: load [module.js:~447] [pc=0x31a5c587cc36] (this=0x12cc82d850e1 <a Module with map 0x34b7d5a181b9>#2#,filename=0x12cc82d850a9 <String[118]: /Users/tal.woolf/developer/frontend/docker-test/node_modules/fsevents/lib/binding/Release/node-v48-darwin-x64/fse.node>)
    3: tryModuleLoad(aka tryModuleLoad) [module.js:415] [pc=0x31a5c543899d] (this=0x641b9e04189 <undefined>,module=0x12cc82d850e1 <a Module with map 0x34b7d5a181b9>#2#,filename=0x12cc82d850a9 <String[118]: /Users/tal.woolf/developer/frontend/docker-test/node_modules/fsevents/lib/binding/Release/node-v48-darwin-x
==== C stack trace ===============================

 1: v8::Template::Set(v8::Local<v8::Name>, v8::Local<v8::Data>, v8::PropertyAttribute)
 2: fse::FSEvents::Initialize(v8::Local<v8::Object>)
 3: node::DLOpen(v8::FunctionCallbackInfo<v8::Value> const&)
 4: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo<v8::Value> const&))
 5: v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::(anonymous namespace)::BuiltinArguments<(v8::internal::BuiltinExtraArguments)1>)
 6: v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*)
 7: 0x31a5c530961b
 8: 0x31a5c5dec944
(node) v8::ObjectTemplate::Set() with non-primitive values is deprecated
(node) and will stop working in the next major release.

==== JS stack trace =========================================

Security context: 0x641b9ec9fa9 <JS Object>#0#
    1: .node [module.js:568] [pc=0x31a5c5dec944] (this=0x766c05fe979 <an Object with map 0x34b7d5a90559>#1#,module=0x12cc82d850e1 <a Module with map 0x34b7d5a181b9>#2#,filename=0x12cc82d850a9 <String[118]: /Users/tal.woolf/developer/frontend/docker-test/node_modules/fsevents/lib/binding/Release/node-v48-darwin-x64/fse.node>)
    2: load [module.js:~447] [pc=0x31a5c587cc36] (this=0x12cc82d850e1 <a Module with map 0x34b7d5a181b9>#2#,filename=0x12cc82d850a9 <String[118]: /Users/tal.woolf/developer/frontend/docker-test/node_modules/fsevents/lib/binding/Release/node-v48-darwin-x64/fse.node>)
    3: tryModuleLoad(aka tryModuleLoad) [module.js:415] [pc=0x31a5c543899d] (this=0x641b9e04189 <undefined>,module=0x12cc82d850e1 <a Module with map 0x34b7d5a181b9>#2#,filename=0x12cc82d850a9 <String[118]: /Users/tal.woolf/developer/frontend/docker-test/node_modules/fsevents/lib/binding/Release/node-v48-darwin-x
==== C stack trace ===============================

 1: v8::Template::Set(v8::Local<v8::Name>, v8::Local<v8::Data>, v8::PropertyAttribute)
 2: fse::FSEvents::Initialize(v8::Local<v8::Object>)
 3: node::DLOpen(v8::FunctionCallbackInfo<v8::Value> const&)
 4: v8::internal::FunctionCallbackArguments::Call(void (*)(v8::FunctionCallbackInfo<v8::Value> const&))
 5: v8::internal::MaybeHandle<v8::internal::Object> v8::internal::(anonymous namespace)::HandleApiCallHelper<false>(v8::internal::Isolate*, v8::internal::(anonymous namespace)::BuiltinArguments<(v8::internal::BuiltinExtraArguments)1>)
 6: v8::internal::Builtin_HandleApiCall(int, v8::internal::Object**, v8::internal::Isolate*)
 7: 0x31a5c530961b
 8: 0x31a5c5dec944

FOUC when using HMR with CSS source-map.

When I use hot-module-reloading with sourcemaps I see what used to be inline style tags in the head turn into link tags with blob: hrefs. For some reason this change is causing a flash of unstyled content before the link tags are injected into the head.

Are there any workarounds for this?

base64 encoded output???

I am getting base64 encoded code when using 1.5.0/1.5.1 (with webpack 1 and webpack-hot-middleware). Works just fine with 1.2.0 - 1.4.0.
So, basically, in dev mode, when I go to http://localhost:3000/static/app.js I should see something like

/******/ (function(modules) { // webpackBootstrap
/******/    var parentHotUpdateCallback = this["webpackHotUpdate"];
/******/    this["webpackHotUpdate"] = 
....

instead I get

"LyoqKioqKi8gKGZ1bmN0aW9uKG1vZHVs...
...
...qKiovIF0pOw=="

which is the base64 encoding of the app code.
Any idea what's going on?

req.path is sometimes not defined

As of #78, I am noticing that req.path is not always defined. I am using Express 4 here and have found a little information, but it doesn't explain the why. The OP mentions "positioning of middleware", but I am unsure how that might trigger this bug. Overall, I'm wondering what the advantage is of using req.path vs req.url. Here's the stack trace:

TypeError: Cannot read property 'indexOf' of undefined
    at getFilenameFromUrl (/Users/stephenmarshall/code/singular-web-server/node_modules/webpack-dev-middleware/middleware.js:129:9)
    at webpackDevMiddleware (/Users/stephenmarshall/code/singular-web-server/node_modules/webpack-dev-middleware/middleware.js:175:18)
    at call (/Users/stephenmarshall/code/singular-web-server/node_modules/browser-sync/node_modules/connect/index.js:239:7)
    at next (/Users/stephenmarshall/code/singular-web-server/node_modules/browser-sync/node_modules/connect/index.js:183:5)
    at handleIe (/Users/stephenmarshall/code/singular-web-server/node_modules/browser-sync/node_modules/foxy/lib/utils.js:191:5)
    at call (/Users/stephenmarshall/code/singular-web-server/node_modules/browser-sync/node_modules/connect/index.js:239:7)
    at next (/Users/stephenmarshall/code/singular-web-server/node_modules/browser-sync/node_modules/connect/index.js:183:5)
    at next (/Users/stephenmarshall/code/singular-web-server/node_modules/browser-sync/node_modules/connect/index.js:161:14)
    at Function.handle (/Users/stephenmarshall/code/singular-web-server/node_modules/browser-sync/node_modules/connect/index.js:186:3)
    at Server.app (/Users/stephenmarshall/code/singular-web-server/node_modules/browser-sync/node_modules/connect/index.js:51:37)
    at Server.<anonymous> (/Users/stephenmarshall/code/singular-web-server/node_modules/browser-sync/node_modules/socket.io/node_modules/engine.io/lib/server.js:434:22)
    at Server.<anonymous> (/Users/stephenmarshall/code/singular-web-server/node_modules/browser-sync/node_modules/socket.io/lib/index.js:260:16)
    at emitTwo (events.js:87:13)
    at Server.emit (events.js:172:7)
    at HTTPParser.parserOnIncoming [as onIncoming] (_http_server.js:528:12)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:88:23)

How to build files for production?

Hi,

I'm using the middleware and it works really smooth for development. As far as I understood, the middleware serves the files from the memory. But how do I build the files for development? How can I put them on disk? I could not figure it out.

Thanks for your help!
Jan

'indexOf' of undefined on url.indexOf(localPrefix)

Hi,

I just update to v1.6.0 and a error occurred

TypeError: Cannot read property 'indexOf' of undefined
   at getFilenameFromUrl (/home/zckrs/project/node_modules/webpack-dev-middleware/middleware.js:129:9)
   at webpackDevMiddleware (/home/zckrs/project/node_modules/webpack-dev-middleware/middleware.js:174:18)
   at call (/home/zckrs/project/node_modules/connect/index.js:239:7)
   at next (/home/zckrs/project/node_modules/connect/index.js:183:5)
...
...

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.