node.js – 如何使用socket.io和webpack-hot-middleware?

我有一个使用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\u0026amp;transport=polling\u0026amp;t=1446911862461-0并且这些请求失败。

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

这是什么worked for me in an app I’m working on我在同一个快递服务器上使用webpack热重新加载socket.io。

你的package.json的添加:

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

在您的webpack配置的插件部分:

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

我发布了一个这个问题的赏金,以帮助这个问题得到回答,虽然我已经为自己的应用程序工作了。

http://stackoverflow.com/questions/33584724/how-to-use-socket-io-together-with-webpack-hot-middleware

本站文章除注明转载外,均为本站原创或编译
转载请明显位置注明出处:node.js – 如何使用socket.io和webpack-hot-middleware?