__webpack_hmr goes to the wrong port and fails

9.3k views Asked by At

I am trying to get hot-reloading to work with my setup. Currently, it works like so --

server.js

// this is the main server, which connects to db, serves react components, etc

const app = express();

app.get('/:params?*', (req, res) => {
  res.status(200).send(`
    <!doctype html>
    <html>
      <head>
        <meta charset="utf-8">
      </head>
      <body>
        hi
        <script src="http://localhost:3000/build/client.js"></script>
      </body>
    </html>
  `);
});

...
app.listen(5000);

gulpfile.babel.js

const CLIENT_DEV_CONFIG = {
  entry: [
    CLIENT_ENTRY,
    'webpack-hot-middleware/client',
    'eventsource-polyfill',
  ],
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
  ],
  output: {
    ...CLIENT_OUTPUT,
    publicPath: 'http://localhost:3000/build/',
  },
  module: {
    loaders: [BABEL_LOADER]
  },
}

gulp.task('client-watch', done => {
  console.log(CLIENT_DEV_CONFIG.output.publicPath);
  const opts = {
    hot: true,
    publicPath: CLIENT_DEV_CONFIG.output.publicPath,
    headers: {'Access-Control-Allow-Origin': '*'},
  };
  const app = new express();
  const compiler = webpack(CLIENT_DEV_CONFIG);
  app.use(webpackDevMiddleware(compiler, opts));
  app.use(webpackHotMiddleWare(compiler));
  app.listen(3000, (err) => {
    console.log(err || '[webpack-hot-devserver] running on 3000');
    done();
  });
});

now,

  • If I visit localhost:5000. It works
  • If I visit localhost:3000/build/client.js, it also works

But, if I update something I don't get live updates, I need to refresh... :(

Looking at the network tab, I see a failing request to http://localhost:5000/__webpack_hmr, and I am thinking this could be the causer.

http://localhost:5000/__webpack_hmr should actually be http://localhost:3000/__webpack_hmr

However, I am not sure how to correct this

1

There are 1 answers

3
Stepan Parunashvili On BEST ANSWER

You can specify the URL in the webpack config in the line in the entry array as seen below:

const CLIENT_DEV_CONFIG = {
  entry: [
    CLIENT_ENTRY,
    `webpack-hot-middleware/client?path=${HOT_SERVER_URL}/__webpack_hmr`,
    'eventsource-polyfill',
  ],
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
  ],
  output: {
    ...CLIENT_OUTPUT,
    publicPath: `${HOT_SERVER_URL}/build/`,
  },
  module: {
    loaders: [
      {
        ...BABEL_LOADER,
        query: {...BABEL_QUERY, presets: [...BABEL_QUERY.presets, 'react-hmre']},
      },
    ],
  },
}

So this line in particular:

`webpack-hot-middleware/client?path=${HOT_SERVER_URL}/__webpack_hmr`,

The path option allows setting the location that hot module reload should hit to access the __webpack_hmr endpoint. One could for example set it to:

'webpack-hot-middleware/client?path=//localhost:3000/__webpack_hmr'