與打包器搭配使用
雖然不如前端打包常見,但完全可以為伺服器建立一個套件。
Webpack 5
不提供用戶端檔案
安裝
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
套件中的兩個選用相依性。您也可以使用下列方式將它們設定為「外部」
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.dev.org.tw/configuration/externals/
包含提供用戶端檔案
在這種情況下,我們必須使用 Asset 模組 並覆寫 Socket.IO 伺服器的 sendFile
函式
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",
},
],
},
};