如何将socket.io与webpack-hot-middleware一起使用?

时间:2015-11-07 16:02:53

标签: node.js express socket.io webpack koa

我有一个使用webpack-dev-middleware和webpack-hot-middleware进行热模块替换(HMR)的Koa服务器,因此中间件使用websocket将更改推送到客户端。

但是我的应用程序代码也需要在客户端和Koa服务器之间拥有自己的websocket连接。我不知道如何实现这一目标?似乎这两者是相互矛盾的。我能和他们并排吗?

我的服务器代码看起来像这样

const compiler = webpack(webpackConfig)
const app = new Koa()

app.use(webpackDevMiddleware(compiler, {
  quiet: true,
  noInfo: true
  stats: {
    colors: true,
    reasons: true
  }
})))

app.use(webpackHotMiddleware(compiler))

const server = require('http').createServer(app.callback())
const io = require('socket.io')(server)
io.on('connection', function() { console.log('socket connection!!') })

和我的客户一样

import Client from 'socket.io-client'
const io = Client()
io.on('connection', (socket) => {
  console.log('+++ io connected! ++++')
  io.on('disconnect', () => { console.log('disconnected', socket) })
})

HMR套接字工作正常,但另一个正在尝试与之交谈 GET /socket.io/?EIO=3&transport=polling&t=1446911862461-0这些请求失败了。

如何创建不与HMR套接字冲突的websocket?

1 个答案:

答案 0 :(得分:12)

这是worked for me in an app I'm working on我在同一个快递服务器上使用webpack hot reloading + socket.io的地方。

添加到package.json

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

在您的webpack配置的plugins部分:

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

快递应用程序的设置:

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);
});

我发布了这个问题的赏金来帮助这个问题得到解答,尽管我已经让它适用于我自己的应用。