Simple to use cocosCreator in the Protobuf

Simple to use cocosCreator in the Protobuf

proto file formats:

 

pro1.jpeg

Preparation Tool:

  1. cocosCreator
  2. webStorm or VSCode
  3. Installation node.js
  4. Download protobufjs6.8.6

step:

  1. Protobufjs mounted to the global
    npm install -g protobufjs
    using npm install -g module mounted to the global parameters, the main purpose is to provide convenience pbjs protobufjs command line tool. pbjs proto original file can be converted into json, js, so as to provide different loading proto way, we can choose to use, as well as pbts according to their actual situation, to the js file after conversion into ts
  2. Locate the downloaded protobuf.js

Files in \ nodejs \ node_modules \ protobufjs \ dist in

 

image.png

Creator Drag this file to the project and import plug-ins

pro4.jpeg
  1. Open command in preservation proto file directory execute the following command line


    pro5.jpeg

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

This code may be all of the files in .proto into a file proto.js

  1. Then proto.js file in the code directory


    pro6.jpeg
  2. Modify proto.js in protobuf references:

pro7.jpeg

Because protobuf has been set up as plug-in

  1. If you want to use the TS format can be achieved by protobufjs6 new features
    execute the following command:

PBTs -o proto.d.ts proto.js

Note: This proto.d.ts must have .d

Now style code directory structure is such

pro8.jpeg
  1. Test use:
pro9.jpeg
pro10.jpeg
pro11.jpeg
pro12.jpeg

经过测试在手机上也是可以正常运行的

第二种方式:

由于现在工程中使用的TS,为了有更好的效果,所以还有另一种方式来依赖protobufjs6

1.安装protobufjs到全局

npm install -g protobufjs

使用npm install -g 参数将模块安装到全局,目的主要是方便使用protobufjs提供的pbjs命令行工具。pbjs可以将proto原文件转换成json、js等,以提供不同的加载proto的方式,我们可以根据自己的实际情况选择使用,还有pbts,用来将转化后的js文件转为ts

  1. 打开工程目录执行命令行:

npm init

执行后一路回车会在工程目录下生成package.json

  1. 在工程目录中执行命令行:

npm install protobufjs

会生成protobufjs的依赖库

pro13.jpeg

4.在保存proto文件的目录下打开命令行执行如下命令

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

pro14.jpeg

这句代码可以将文件中所有的.proto文件转化为一个proto.js文件

pro15.jpeg

这个不用修改proto文件

6.如果想使用TS格式可以通过protobufjs6新功能来实现
执行如下命令:

pbts -o proto.d.ts proto.js

注意:这里proto.d.ts一定要有.d

现在代码目录结构的样式就是这样的

pro16.jpeg

然后就可以使用了,而且代码提示很友好~

pro17.jpeg
pro18.jpeg

如果有问题请参考这些网址:

https://www.jianshu.com/p/1b90dd4bcb0a

http://forum.cocos.com/t/cocos-creator-protobufjs-ts/47687

https://www.jianshu.com/u/ba2c5d0f4939

 

来源:https://www.jianshu.com/p/f727f78dcc76

 

Guess you like

Origin www.cnblogs.com/gao88/p/11701320.html
Recommended