How to use socket.io together with webpack-hot-middleware?

折月煮酒 提交于 2019-12-03 01:31:50

Here's what worked for me in an app I'm working on where I'm using webpack hot reloading + socket.io on the same express server.

Additions to your package.json:

"webpack-dev-middleware": "^1.4.0",
"webpack-hot-middleware": "^2.6.0"

In the plugins section of your webpack config:

plugins: [
   new webpack.optimize.OccurenceOrderPlugin(),
   new webpack.HotModuleReplacementPlugin(),
   new webpack.NoErrorsPlugin(),
],

Setup for the express app:

const http = require('http');
const express = require('express');

const webpack = require('webpack');
const webpackConfig = require('./webpack.config');
const compiler = webpack(webpackConfig);

// Create the app, setup the webpack middleware
const app = express();
app.use(require('webpack-dev-middleware')(compiler, {
  noInfo: true,
  publicPath: webpackConfig.output.publicPath,
}));
app.use(require('webpack-hot-middleware')(compiler));

// You probably have other paths here
app.use(express.static('dist'));

const server = new http.Server(app);
const io = require('socket.io')(server);

const PORT = process.env.PORT || 8090;

server.listen(PORT);

io.on('connection', (socket) => {
  // <insert relevant code here>
  socket.emit('mappy:playerbatch', playerbatch);
});

I posted a bounty for this question to help this question get answered, though I've got it working for my own app.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!