什么是 protobuf
protobuf(Protocol Buffers) 是一种开源的,易于拓展的结构化序列机制(类似于XML,但是体积更小,传输编译更快,使用编辑更简单)。你可以定义你想要的数据格式,然后用工具轻松的生成任意编程语言的代码——读写相关的结构数据。
使用环境
浏览器/nodejs环境
为什么要写这篇文章
- google 到的相关教程都是直接使用 protobufjs api,而该 api 不太容易使用,也非常繁琐;
- webpack 环境下
protobuf.load
不好用,需要多余的配置; - 不支持 typescript。
目标
直接使用工具从 .proto
文件生成 .ts
相关代码,不需要手动调用 protobufjs
相关 api。
步骤
- 安装 protoc;
- 设置
protoc
的环境变量; - 本地或者全局安装
ts-proto
包; - 执行脚本转换
.proto
文件protoc --plugin=./node_modules/ts-proto/protoc-gen-ts_proto --ts_proto_out=./ts --proto_path=./proto ./proto/example.proto
(如果 proto 文件中有依赖的话会自行解析,多个独立的文件要再次执行); - 如果是 windows 平台的话需要将
--plugin=...
改为--plugin=protoc-gen-ts_proto=.\node_modules\.bin\protoc-gen-ts_proto.cmd
。
输入输出文件示例
输入 example.proto
syntax = 'proto3';
message Point{
float x = 1;//x坐标
float y = 2;//y坐标
}
输出 example.ts
export interface Point {
/** x坐标 */
x: number;
/** y坐标 */
y: number;
}
export const Point {
// 二进制编码
encode(message: Point, ...) {
...
},
// 二进制解码
decode(input: Reader | Uint8Array, ...): Point {
...
},
fromJSON,
toJSON,
fromPartial,
}
注意
- 如果需要 js 文件的话,将 ts 转换一下即可;
- 获取到的 protobuf 转码(读取/写入)出错的话,可能是使用了错误的格式,或者
.proto
文件过时了。