バンドラーでの使用
フロントエンドのバンドルよりも一般的ではありませんが、サーバのバンドルを作成することは十分可能です。
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 パッケージの 2 つのオプションの依存関係です。これらは
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.dokyumento.jp/configuration/externals/
クライアントファイルをサーブするには
その場合、アセットモジュール を使用して 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",
      },
    ],
  },
};