与捆绑器一起使用

虽然不如前端捆绑常见,但完全可以为服务器创建捆绑。

Webpack 5

不提供客户端文件

安装:

  1. npm install -D webpack webpack-cli socket.io bufferutil utf-8-validate

index.js

  1. const { Server } = require("socket.io");
  2. const io = new Server({
  3. serveClient: false
  4. });
  5. io.on("connection", socket => {
  6. console.log(`connect ${socket.id}`);
  7. socket.on("disconnect", (reason) => {
  8. console.log(`disconnect ${socket.id} due to ${reason}`);
  9. });
  10. });
  11. io.listen(3000);

webpack.config.js

  1. const path = require("path");
  2. module.exports = {
  3. entry: "./index.js",
  4. target: "node",
  5. mode: "production",
  6. output: {
  7. path: path.resolve(__dirname, "dist"),
  8. filename: "index.js",
  9. }
  10. };

注意:bufferutilutf-8-validatews包中的两个可选依赖项。您还可以使用以下方法将它们设置为“外部”:

  1. const path = require("path");
  2. module.exports = {
  3. entry: "./index.js",
  4. target: "node",
  5. mode: "production",
  6. output: {
  7. path: path.resolve(__dirname, "dist"),
  8. filename: "index.js",
  9. },
  10. externals: {
  11. bufferutil: "bufferutil",
  12. "utf-8-validate": "utf-8-validate",
  13. },
  14. };

文档:https://webpack.js.org/configuration/externals/

包括提供客户端文件

在这种情况下,我们将不得不使用Asset modules并覆盖sendFileSocket.IO 服务器的功能:

index.js

  1. const { Server } = require("socket.io");
  2. const clientFile = require("./node_modules/socket.io/client-dist/socket.io.min?raw");
  3. const clientMap = require("./node_modules/socket.io/client-dist/socket.io.min.js.map?raw");
  4. Server.sendFile = (filename, req, res) => {
  5. res.end(filename.endsWith(".map") ? clientMap : clientFile);
  6. };
  7. const io = new Server();
  8. io.on("connection", socket => {
  9. console.log(`connect ${socket.id}`);
  10. socket.on("disconnect", (reason) => {
  11. console.log(`disconnect ${socket.id} due to ${reason}`);
  12. });
  13. });
  14. io.listen(3000);

webpack.config.js

  1. const path = require("path");
  2. module.exports = {
  3. entry: "./index.js",
  4. target: "node",
  5. mode: "production",
  6. output: {
  7. path: path.resolve(__dirname, "dist"),
  8. filename: "index.js",
  9. },
  10. module: {
  11. rules: [
  12. {
  13. resourceQuery: /raw/,
  14. type: "asset/source",
  15. },
  16. ],
  17. },
  18. };