什么是 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
文件過時了。