Webpack-hot-middleware: HMR client not starting

Created on 24 May 2016  路  25Comments  路  Source: webpack-contrib/webpack-hot-middleware

Hi, I'm wondering if I can get some help with debugging an issue I have with HMR?

My machine is Windows 10 and my project uses webpack-dev-middleware and webpack-hot-middleware, based on this boilerplate: https://github.com/choonkending/react-webpack-node/

If I pull a fresh copy of that repo, HMR works exactly as it should, so the problem appears to be something I've added or changed, but I'm having trouble figuring out what that is.

In my project (https://github.com/ReallySmall/react-node-stackduino), the server side of HMR appears to still be working as expected. if I go to /__webpack_hmr I see the heartbeat - and whenever I update code I see that change reflected at /__webpack_hmr and in my cmd window I get the 'webpack built' notification.

However in my Chrome console I don't see any HMR activity at all - none of the usual messages to say HMR is initialised, connected or updated. The console remains blank. So HMR is all happening in the background, but the front end client isn't initialising.

Are there any common reasons why the HMR client would fail to start?

Thanks in advance for any help.

Cheers
Richard

awaiting-input

Most helpful comment

Hi,

This strange bug had happened to me too. I'm using Windows 10 on two different machines and the same setup works on an older and slower PC and it doesn't work on a new and much powerful laptop.

I found that when starting the server with:

app.listen(3000, 'localhost', function (err) {
  if (err) {
    console.log(err);
    return;
  }

  console.log('Server is running at http://localhost:3000');
});

the /__webpack_hmr endpoint stays in pending mode and after a few seconds it's cancelled.

If I remove the 'localhost' part:

app.listen(3000, function (err) {
  if (err) {
    console.log(err);
    return;
  }

  console.log('Server is running at http://localhost:3000');
});

... it works as expected on both machines.

I can reproduce it with this repo: https://github.com/knowbody/react-boilerplate, which has a very simple setup. By reproducing I mean, it works on the PC but not on the laptop, unless I remove the host parameter.

Hope it helps,
Raul.

All 25 comments

This seems to be happening to a bunch of people, most commonly on Windows.

I've never been able to reproduce it myself, so info you can provide is much appreciated!

Can you see anything in the network tab of chrome related to /__webpack_hmr ? When you said you went to that URL and saw the heartbeat, was that in the browser or via something like curl?

There might be some stuff you can try in #36

Viewing /__webpack_hmr either through cURL or the browser directly I see the same thing - the heartbeat, or the 'patch content' as soon as I change any code. As far as I can tell that appears to be working correctly.

I don't see anything in the network tab related to /__webpack_hmr.

If I include a conditional if(module.hot) in my code, this never gets executed, suggesting something is amiss - but I'm not sure what reasons what cause that not to be the case? It's tricky to debug as there are no errors :)

Ah, interesting - can you share your webpack.config.js - it sounds like you might be missing the client entrypoint

Here it is:

var path = require('path');
var webpack = require('webpack');
var assetsPath = path.join(__dirname, '..', 'public', 'assets');
var hotMiddlewareScript = 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000&reload=true';

console.log('dev client config in use');

var commonLoaders = [
  {
    /*
     * TC39 categorises proposals for babel in 4 stages
     * Read more http://babeljs.io/docs/usage/experimental/
     */
    test: /\.js$|\.jsx$/,
    loader: 'babel',
    // Reason why we put this here instead of babelrc
    // https://github.com/gaearon/react-transform-hmr/issues/5#issuecomment-142313637
    query: {
      "presets": ["react-hmre", "es2015", "react", "stage-0"]
    },
    include: path.join(__dirname, '..', 'app'),
    exclude: path.join(__dirname, '/node_modules/')
  },
  {
    test: /\.(png|jpg|jpeg|gif|svg)$/,
    loader: 'url',
    query: {
        name: '[hash].[ext]',
        limit: 10000,
    }
  },
  {
    test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
    loader: 'url-loader?limit=10000&mimetype=application/font-woff'
  },
  {
    test: /\.(ttf|eot|svg)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
    loader: 'file-loader'
  },
  { test: /\.html$/, 
    loader: 'html-loader' 
  }
];

var postCSSConfig = function() {
  return [
    require('postcss-import')({
      path: path.join(__dirname, '..', 'app', 'css'),
      // addDependencyTo is used for hot-reloading in webpack
      addDependencyTo: webpack
    }),
    require('postcss-simple-vars')(),
    // Unwrap nested rules like how Sass does it
    require('postcss-nested')(),
    //  parse CSS and add vendor prefixes to CSS rules
    require('autoprefixer')({
      browsers: ['last 2 versions', 'IE > 8']
    }),
    // A PostCSS plugin to console.log() the messages registered by other
    // PostCSS plugins
    require('postcss-reporter')({
      clearMessages: true
    })
  ];
};

module.exports = {
    // eval - Each module is executed with eval and //@ sourceURL.
    devtool: 'eval',
    // The configuration for the client
    name: 'browser',
    /* The entry point of the bundle
     * Entry points for multi page app could be more complex
     * A good example of entry points would be:
     * entry: {
     *   pageA: "./pageA",
     *   pageB: "./pageB",
     *   pageC: "./pageC",
     *   adminPageA: "./adminPageA",
     *   adminPageB: "./adminPageB",
     *   adminPageC: "./adminPageC"
     * }
     *
     * We can then proceed to optimize what are the common chunks
     * plugins: [
     *  new CommonsChunkPlugin("admin-commons.js", ["adminPageA", "adminPageB"]),
     *  new CommonsChunkPlugin("common.js", ["pageA", "pageB", "admin-commons.js"], 2),
     *  new CommonsChunkPlugin("c-commons.js", ["pageC", "adminPageC"]);
     * ]
     */
    context: path.join(__dirname, '..', 'app'),
    // Multiple entry with hot loader
    // https://github.com/glenjamin/webpack-hot-middleware/blob/master/example/webpack.config.multientry.js
    entry: {
      app: ['./client', hotMiddlewareScript]
    },
    output: {
      // The output directory as absolute path
      path: assetsPath,
      // The filename of the entry chunk as relative path inside the output.path directory
      filename: '[name].js',
      // The output path from the view of the Javascript
      publicPath: '/assets/'
    },
    module: {
      loaders: commonLoaders.concat([
        { test: /\.css$/,
          loader: 'style!css!postcss-loader'
        }
      ])
    },
    resolve: {
      extensions: ['', '.js', '.jsx', '.css'],
      modulesDirectories: [
        'app', 'node_modules'
      ]
    },
    plugins: [
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NoErrorsPlugin(),
        new webpack.DefinePlugin({
          __DEVCLIENT__: true,
          __DEVSERVER__: false
        }),
        new webpack.ProvidePlugin({ 
          $: 'jquery', 
          jQuery: 'jquery'
        })
    ],
    postcss: postCSSConfig
};

It's more or less the same as the boilerplate version: https://github.com/choonkending/react-webpack-node/blob/master/webpack/webpack.config.dev-client.js, except I've added a few additional loaders.

Does anything look obviously amiss?

That all looks fine, if you open up the bundle in a text editor can you see the HMR client code?

Does it show up in the browser debugger? Can you put a breakpoint around the point it tries to connect to the server?

Sorry - which bundle?

I've verified that the reference to client.js is correct in my project. I also added a console.log to the top of that file, which doesn't appear on run - so it does appear that the client isn't getting bundled.

The bundle produced by webpack.

I can't see any reason that would fail quietly - it should either blow up because it can't find hot-middleware, or work.

I was afraid you were going to say that :D

Another oddity is the app.js bundle is minified, when really it shouldn't be. Starting to wonder whether my problem is related to environment variables...

Double-checked it's nothing in /app by copying in the folder from the working boilerplate. Still no HMR so that narrows it down a bit more.

Can you share your server code, or a larger sample? Are you definitely passing that config through to the webpack compiler intact?

I wondered that too - I've previously added a console.log() to the dev client webpack config to verify that it is the one being used - and that does appear to be the case.

Also if I deliberately supply a bad path to HMR client.js in the Webpack dev config, the dev task immediately fails - which also points to the config being at least looked at by the compiler(?)

My server code is here: https://github.com/ReallySmall/react-node-stackduino/blob/master/server/index.js

I suspect you might have a similar issue to https://github.com/glenjamin/webpack-hot-middleware/issues/84 from when you bundle the server code.

Thanks for that, I'll have a read through. Interestingly if I paste the dev client config into the dev server config, HMR then sort of works - in the sense that the client then appears in the console/ network, although nothing quite works as it should. I think the client config is meant to over-ride the dev server config when invoked, but for some reason it isn't.

More specifically, if I run dev server first, then over-write the dev-server config with the dev-client config, when the task restarts, HMR then works perfectly. I can't quite work out why at the moment, but I'm much closer to solving it now - thanks very much for all the feedback!

From what I can tell, the Dev server bundle bundles the server code, which you then run.

The compiled server code then uses webpack middleware to serve up the client bundle.

Bundling the sever code can mangle the config file, so the fix is to exclude client config from the sever bundle.

Ok, thank you. I think I sort of understand, but perhaps not as it seems to me that the client config is already excluded from the server bundle - in the sense that it isn't included until run-time? If I am misunderstanding (quite likely), how would I go about excluding it?

This task Creates a webpack bundle of your server code with server/index.js as the entry point. server/index.js imports the client config.

This means the client config gets evaluated at server build time, which can lead to problems. To exclude it you need to use the IgnorePlugin in https://github.com/choonkending/react-webpack-node/blob/master/webpack/webpack.config.dev-server.js#L63

Hi,

This strange bug had happened to me too. I'm using Windows 10 on two different machines and the same setup works on an older and slower PC and it doesn't work on a new and much powerful laptop.

I found that when starting the server with:

app.listen(3000, 'localhost', function (err) {
  if (err) {
    console.log(err);
    return;
  }

  console.log('Server is running at http://localhost:3000');
});

the /__webpack_hmr endpoint stays in pending mode and after a few seconds it's cancelled.

If I remove the 'localhost' part:

app.listen(3000, function (err) {
  if (err) {
    console.log(err);
    return;
  }

  console.log('Server is running at http://localhost:3000');
});

... it works as expected on both machines.

I can reproduce it with this repo: https://github.com/knowbody/react-boilerplate, which has a very simple setup. By reproducing I mean, it works on the PC but not on the laptop, unless I remove the host parameter.

Hope it helps,
Raul.

Just adding, I have problems on my macbook with HMR in an angular2-webpack project

@raulmatei comment fixed my issue! Great stuff. I'd like to know why this is happening though

There is also a similar issue, removing the reload=true flag from the webpack-hot-client makes the HMR to start, more info here with repro repo https://github.com/gaearon/react-hot-loader/issues/432

/cc @glenjamin

Edit: Updated CC

Hi! I've encounted the same problem. Fortunately, I've solved my problem. Previously, I believed that the Win10 led to the bug that HMR not trigger . Now since I've experienced on my colleague's Mac and use vscode instead of webstorm, the key is the "autosave" of the webstorm. I think if u use vscode sublime autom etc, your HMR will reburn

Hi, Actually I'm encountering the localhost:[port]/__webpack_hmr CONNECTION_REFUSED error in the console when I try to run it. If I press a refresh a couple of times, it shows the HMR connected but when I make a change to a module. It goes on building and built in the browser's console. I'm trying to use Angular 2 with Webpack with HMR from scratch and I'm not using webpack-dev-server.

Hello, i had the same problem, and i just needed to remove the definePlugin from webpack to make HMR work ..

Just a heads up I spent way too long figuring out that I had been mixing up webpack-dev-middleware with webpack-hot-middleware , hopefully this helps someone else too!

Was this page helpful?
0 / 5 - 0 ratings

Related issues

chopfitzroy picture chopfitzroy  路  4Comments

erikakers picture erikakers  路  11Comments

DmitryVolkovTulaco picture DmitryVolkovTulaco  路  4Comments

drewwyatt picture drewwyatt  路  8Comments

Yizhachok picture Yizhachok  路  6Comments