Skip to main content
Version: 4.x

客户端与打包器的使用

你将在下面找到用于将客户端库与不同打包器打包在一起的配置:

¥You will find below the configuration for bundling the client library with different bundlers:

Webpack 5

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

¥Documentation: https://webpack.js.org/concepts/

浏览器

¥Browser

安装:

¥Installation:

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

webpack.config.js

module.exports = {
entry: "./index.js",
output: {
filename: "bundle.js",
},
mode: "production",
node: false,
module: {
rules: [
{
test: /\.m?js$/,
use: {
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"], // ensure compatibility with older browsers
plugins: ["@babel/plugin-transform-object-assign"], // ensure compatibility with IE 11
},
},
},
{
test: /\.js$/,
loader: "webpack-remove-debug", // remove "debug" package
},
],
},
};

作为参考,以下是 webpack-bundle-analyzer 包的输出:

¥For reference, here is the output of the webpack-bundle-analyzer package:

Output of the webpack-bundle-analyzer package

Node.js

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

¥To use the client in a Node.js environment (server to server connection), here is the configuration:

安装:

¥Installation:

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

webpack.config.js

module.exports = {
entry: "./index.js",
output: {
filename: "bundle.js",
},
mode: "production",
target: "node",
externals: {
bufferutil: "bufferutil",
"utf-8-validate": "utf-8-validate",
},
};

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

¥Note: without setting target: "node", you will likely encounter the following error:

ReferenceError: document is not defined

Rollup.js

文档:https://rollup.nodejs.cn/guide/en/

¥Documentation: https://rollup.nodejs.cn/guide/en/

浏览器

¥Browser

安装:

¥Installation:

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

rollup.config.js

import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import babel from "@rollup/plugin-babel";
import { uglify } from "rollup-plugin-uglify";

export default {
input: "index.js",
output: {
file: "bundle.js",
format: "cjs",
},
plugins: [
resolve({
browser: true,
}),
commonjs(),
babel({
include: ["**.js", "node_modules/**"],
babelHelpers: "bundled",
presets: ["@babel/preset-env"],
}),
uglify(),
],
};

Node.js

安装:

¥Installation:

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

rollup.config.js

import resolve from "@rollup/plugin-node-resolve";
import commonjs from "@rollup/plugin-commonjs";
import { uglify } from "rollup-plugin-uglify";

export default {
input: "index.js",
output: {
file: "bundle.js",
format: "cjs",
},
plugins: [
resolve({
preferBuiltins: true,
}),
commonjs(),
uglify(),
],
};