客户端使用构建工具

您将在下面找到客户端使用不同构建工具时的配置:

Webpack 5

文档: https://webpack.js.org/concepts/

Browser

安装:

  1. npm i -D socket.io-client webpack webpack-cli babel-loader @babel/core @babel/preset-env \
  2. @babel/plugin-transform-object-assign webpack-remove-debug

webpack.config.js

  1. module.exports = {
  2. entry: "./index.js",
  3. output: {
  4. filename: "bundle.js",
  5. },
  6. mode: "production",
  7. node: false,
  8. module: {
  9. rules: [
  10. {
  11. test: /\.m?js$/,
  12. use: {
  13. loader: "babel-loader",
  14. options: {
  15. presets: ["@babel/preset-env"], // ensure compatibility with older browsers
  16. plugins: ["@babel/plugin-transform-object-assign"], // ensure compatibility with IE 11
  17. },
  18. },
  19. },
  20. {
  21. test: /\.js$/,
  22. loader: "webpack-remove-debug", // remove "debug" package
  23. },
  24. ],
  25. },
  26. };

作为参考,这里是webpack-bundle-analyzer包的输出:

Output of the webpack-bundle-analyzer package

Node.js

要在 Node.js 环境中使用客户端(服务器到服务器连接),以下是配置:

安装:

  1. npm i -D socket.io-client webpack webpack-cli

webpack.config.js

  1. module.exports = {
  2. entry: "./index.js",
  3. output: {
  4. filename: "bundle.js",
  5. },
  6. mode: "production",
  7. target: "node",
  8. externals: {
  9. bufferutil: "bufferutil",
  10. "utf-8-validate": "utf-8-validate",
  11. },
  12. };

注意:如果不设置 target: "node",可能会遇到如下错误:

  1. ReferenceError: document is not defined

Rollup.js

文档: https://rollupjs.org/guide/en/

Browser

安装:

  1. npm i -D socket.io-client rollup @rollup/plugin-node-resolve @rollup/plugin-commonjs @rollup/plugin-commonjs \
  2. @rollup/plugin-babel rollup-plugin-uglify babel @babel/core @babel/preset-env

rollup.config.js

  1. import resolve from "@rollup/plugin-node-resolve";
  2. import commonjs from "@rollup/plugin-commonjs";
  3. import babel from "@rollup/plugin-babel";
  4. import { uglify } from "rollup-plugin-uglify";
  5. export default {
  6. input: "index.js",
  7. output: {
  8. file: "bundle.js",
  9. format: "cjs",
  10. },
  11. plugins: [
  12. resolve({
  13. browser: true,
  14. }),
  15. commonjs(),
  16. babel({
  17. include: ["**.js", "node_modules/**"],
  18. babelHelpers: "bundled",
  19. presets: ["@babel/preset-env"],
  20. }),
  21. uglify(),
  22. ],
  23. };

Node.js

安装:

  1. npm i -D socket.io-client rollup @rollup/plugin-node-resolve @rollup/plugin-commonjs rollup-plugin-uglify

rollup.config.js

  1. import resolve from "@rollup/plugin-node-resolve";
  2. import commonjs from "@rollup/plugin-commonjs";
  3. import { uglify } from "rollup-plugin-uglify";
  4. export default {
  5. input: "index.js",
  6. output: {
  7. file: "bundle.js",
  8. format: "cjs",
  9. },
  10. plugins: [
  11. resolve({
  12. preferBuiltins: true,
  13. }),
  14. commonjs(),
  15. uglify(),
  16. ],
  17. };