我正在使用Angular Universal,Express和Webpack。我使用这个git repo开始了应用程序:
https://github.com/FrozenPandaz/ng-universal-demo
我似乎无法在main.server.ts中使用socket.io。我可以导入它,但在尝试设置时我收到错误:
...
import * as express from 'express';
import * as socket from 'socket.io';
enableProdMode();
const app = express();
const server = require('http').Server(app);
const io = socket(server);
// . ^^ causes error
app.engine('html', ngExpressEngine({
bootstrap: ServerAppModule
}));
app.set('view engine', 'html');
app.set('views', 'src');
app.use('/', express.static('dist', {index: false}));
server.listen(1337);
app.get('test', (req, res) => {
res.render('../dist/index', {
req: req,
res: res
});
});
io.on('connection', (socket) => {
socket.on('register', (data) => {
socket.join(data);
user = data;
});
});
由于socket(server)
调用而发生错误,就像我发表评论一样,错误不会发生:
/Users/michaelwilson/Code/app/dist/server.js:101828
return /*require.resolve*/(!(function webpackMissingModule() { var e = new Error("Cannot find module \".\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
^
Error: Cannot find module "."
at webpackMissingModule (/Users/michaelwilson/Code/app/dist/server.js:101828:76)
at resolvePath (/Users/michaelwilson/Code/app/dist/server.js:101828:154)
at Server.serveClient (/Users/michaelwilson/Code/app/dist/server.js:101831:25)
at new Server (/Users/michaelwilson/Code/app/dist/server.js:101770:8)
at Server (/Users/michaelwilson/Code/app/dist/server.js:101762:41)
at Object.<anonymous> (/Users/michaelwilson/Code/app/dist/server.js:113993:10)
at __webpack_require__ (/Users/michaelwilson/Code/app/dist/server.js:26:30)
at /Users/michaelwilson/Code/app/dist/server.js:94:18
at Object.<anonymous> (/Users/michaelwilson/Code/app/dist/server.js:97:10)
at Module._compile (module.js:570:32)
[nodemon] app crashed - waiting for file changes before starting...
我不确定还有什么可以尝试,这是Webpack + Socket.io的问题吗?我在同样的问题上找不到其他人......
编辑:我已经跟踪了socket.io库中发生的代码行,它试图进行动态解析:
return /*require.resolve*/(!(function webpackMissingModule() { var e = new Error("Cannot find module \".\""); e.code = 'MODULE_NOT_FOUND'; throw e; }()));
答案 0 :(得分:0)
我设法通过将serveClient
属性设置为false
来解决此错误:
const io = require('socket.io')(server, {
serveClient: false,
wsEngine: 'ws' // uws is not supported since it is a native module
});
https://github.com/socketio/socket.io/tree/master/examples/webpack-build-server https://socket.io/docs/server-api/#server-serveclient-value