如何通过导入加载 proto 文件

n3s*_*uik 5 javascript protocol-buffers proto3 protobuf.js

我正在使用dcodeIO/protobuf.js lib(版本 6.8.4)来解析浏览器中的 protobuf 消息。只要不导入另一个原始文件,我就可以让它使用简单的原始文件。

在主文件中导入其他原始文件会破坏一切。

这就是我所拥有的:

    Error: no such type

at Root.lookupType (http://localhost:63342/xx/build/app/vendor/protobuf/dist/protobuf.js:3463:15)
at http://localhost:63342/xx/build/app/src/app/asset/asset.module.js:320:53
at finish (http://localhost:63342/xx/build/app/vendor/protobuf/dist/protobuf.js:5212:9)
at Root.load (http://localhost:63342/xx/build/app/vendor/protobuf/dist/protobuf.js:5316:9)
at Object.load (http://localhost:63342/xx/build/app/vendor/protobuf/dist/protobuf.js:2547:17)
at new <anonymous> (http://localhost:63342/xx/build/app/src/app/asset/asset.module.js:316:22)
at Object.instantiate (http://localhost:63342/xx/build/app/vendor/angular/angular.js:4786:14)
at $controller (http://localhost:63342/xx/build/app/vendor/angular/angular.js:10607:28)
at Object.<anonymous> (http://localhost:63342/xx/build/app/vendor/angular-ui-router/release/angular-ui-router.js:4081:28)
at http://localhost:63342/xx/build/app/vendor/angular/angular.js:1259:18
Run Code Online (Sandbox Code Playgroud)

GVy*_*yas -1

您需要首先检查 protobuf.load 是否已加载您的组件。如果没有加载,它将无法工作。

您可以将负载更改为loadSync

    var MessageProto = null;
    protobuf.loadSync({root:"assets", file:"api/messageA.proto"}, function(err, root) {
        if (root) { MessageAProto = root.lookupType("com.assets.api.MessageA");
    }});
Run Code Online (Sandbox Code Playgroud)

数据 = MessageProto .decode(rawData);

您可以选择使用静态方法。

    import { AwesomeMessage } from "./bundle.js";

    // example code
    let message = AwesomeMessage.create({ awesomeField: "hello" });
    let buffer  = AwesomeMessage.encode(message).finish();
    let decoded = AwesomeMessage.decode(buffer);
Run Code Online (Sandbox Code Playgroud)

要创建静态文件,请使用

pbjs -t json-module -w commonjs -o bundle.js file1.proto file2.proto