cocos creator + TS + probuf(适配3.0+版本)

  1. 安装protobufjs到全局
npm install -g protobufjs

路径:/Users/qs/.nvm/versions/node/vxx.xx/lib/node_modules/protobufjs

可能报错:

installing semver@^7.1.2
node:child_process:903
    throw err;
    ^

Error: Command failed: npm --silent install semver@^7.1.2
    at checkExecSyncError (node:child_process:826:11)
    at Object.execSync (node:child_process:900:15)
    at modInstall (/usr/local/lib/node_modules/protobufjs/cli/util.js:129:19)
    at Object.exports.setup (/usr/local/lib/node_modules/protobufjs/cli/util.js:140:9)
    at Object. (/usr/local/lib/node_modules/protobufjs/cli/pbjs.js:7:6)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Module.require (node:internal/modules/cjs/loader:1005:19) {
  status: 243,
  signal: null,
  output: [ null, null, null ],
  pid: 13380,
  stdout: null,
  stderr: null
}

解决办法:

cd pb目录下

sudo pbjs -t static-module -w commonjs -o xxx.js xxx.proto
  1. 把protobuf.js拖入工程作为插件

  2. 生成proto.js

pbjs -t static-module -w commonjs -o proto.js *.proto

  1. 修改proto.js中的
// var $protobuf = require("protobufjs/minimal");
var $protobuf = protobuf

注意:proto.js不要作为插件导入到cocos

  1. 生成proto.d.ts
pbts -o proto.d.ts proto.js

示例

新建一个common.proto

package common;
/*
    请求基本信息
*/
message Request {
    required uint32 code = 1;       //操作码
    optional uint32 api  = 2;       //API
}

按照上面流程,生成proto.d.ts文件

  • 封包过程
import {common} from "./proto";
let msg = common["Request"].create(data)
let bytes = common["Request"].encode(msg).finish()
let retArr = new ArrayBuffer(4);
let dv = new DataView(retArr);
dv.setUint32(0, bytes.length, false);
let head  = new Uint8Array(retArr)

let retData = new Uint8Array(bytes.length + 4);
retData.set(head, 0);  // 包头,数据长度4bytes
retData.set(bytes, 4);
socket.send(retData)
  • 解包过程
let uint8Data = new Uint8Array(data);
let headB = uint8Data.slice(0, 4)
let dv = new DataView(headB.buffer)
let head = dv.getUint32(headB, false)
let protoData = uint8Data.slice(4);
let msg = common["Request"].decode(protoData);

creator 3.0+版本使用

creator 3.0以后的版本发现导入proto.d.ts的时候报错了,这里做个微调
tsconfig.json添加

"allowSyntheticDefaultImports": true

直接导入proto.js,不需要转为proto.d.ts

import common from "./proto.js";

参考:
cocos:https://docs.cocos.com/creator/3.0/manual/zh/scripting/modules/example-protobufjs.html
https://kenkao.blog.csdn.net/article/details/108048636?utm_medium=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-8.control&depth_1-utm_source=distribute.pc_relevant.none-task-blog-2%7Edefault%7EBlogCommendFromBaidu%7Edefault-8.control
https://blog.csdn.net/weixin_34120274/article/details/88910293
https://forum.cocos.org/t/topic/107132/6

你可能感兴趣的:(cocos creator + TS + probuf(适配3.0+版本))