与打包器一起使用
虽然不像前端打包那么常见,但完全可以为服务器创建打包。
¥While less common than frontend bundling, it is totally possible to create a bundle for the server.
Webpack 5
不提供客户端文件
¥Without serving the client files
安装:
¥Installation:
npm install -D webpack webpack-cli socket.io bufferutil utf-8-validate
index.js
const { Server } = require("socket.io");
const io = new Server({
serveClient: false
});
io.on("connection", socket => {
console.log(`connect ${socket.id}`);
socket.on("disconnect", (reason) => {
console.log(`disconnect ${socket.id} due to ${reason}`);
});
});
io.listen(3000);
webpack.config.js
const path = require("path");
module.exports = {
entry: "./index.js",
target: "node",
mode: "production",
output: {
path: path.resolve(__dirname, "dist"),
filename: "index.js",
}
};
注意:bufferutil
和 utf-8-validate
是 ws
包中的两个可选依赖。你还可以使用以下命令将它们设置为 "external":
¥Note: bufferutil
and utf-8-validate
are two optional dependencies from the ws
package. You can also set them as "external" with:
const path = require("path");
module.exports = {
entry: "./index.js",
target: "node",
mode: "production",
output: {
path: path.resolve(__dirname, "dist"),
filename: "index.js",
},
externals: {
bufferutil: "bufferutil",
"utf-8-validate": "utf-8-validate",
},
};
文档:https://webpack.js.org/configuration/externals/
¥Documentation: https://webpack.js.org/configuration/externals/
包括提供客户端文件
¥Including serving the client files
在这种情况下,我们必须使用 资源模块 并覆盖 Socket.IO 服务器的 sendFile
函数:
¥In that case, we'll have to use Asset modules and override the sendFile
function of the Socket.IO server:
index.js
const { Server } = require("socket.io");
const clientFile = require("./node_modules/socket.io/client-dist/socket.io.min?raw");
const clientMap = require("./node_modules/socket.io/client-dist/socket.io.min.js.map?raw");
Server.sendFile = (filename, req, res) => {
res.end(filename.endsWith(".map") ? clientMap : clientFile);
};
const io = new Server();
io.on("connection", socket => {
console.log(`connect ${socket.id}`);
socket.on("disconnect", (reason) => {
console.log(`disconnect ${socket.id} due to ${reason}`);
});
});
io.listen(3000);
webpack.config.js
const path = require("path");
module.exports = {
entry: "./index.js",
target: "node",
mode: "production",
output: {
path: path.resolve(__dirname, "dist"),
filename: "index.js",
},
module: {
rules: [
{
resourceQuery: /raw/,
type: "asset/source",
},
],
},
};