关于protobuf 的问题 跪求大佬进来瞅瞅 !!

┬ protobufjs@6.8.8
│ ├── @protobufjs/aspromise@1.1.2
│ ├── @protobufjs/base64@1.1.2
│ ├── @protobufjs/codegen@2.0.4
│ ├── @protobufjs/eventemitter@1.1.0
│ ├─┬ @protobufjs/fetch@1.1.0
│ │ ├── @protobufjs/aspromise@1.1.2 deduped
│ │ └── @protobufjs/inquire@1.1.0 deduped
│ ├── @protobufjs/float@1.0.2
│ ├── @protobufjs/inquire@1.1.0
│ ├── @protobufjs/path@1.1.2
│ ├── @protobufjs/pool@1.1.0
│ ├── @protobufjs/utf8@1.1.0
│ ├── @types/long@4.0.0
│ ├── @types/node@10.14.21
│ └── long@4.0.0
这个是我本地关于protobufjs引用的第三方库···
你保证你引用的库和我一样就可以正常编译出js和ts文件了···

你编译出来的js文件尽量和protobuf.js放到一个文件夹,然后protobuf.js要导入为插件脚本,而生成的js不要导入为插件脚本。

这个我知道 把protobuf.js 和转换的d.ts 和.js文件都是放在同一个目录, 怎么查看自己本地的protobufjs引用的第三方库 我想看看缺失了哪些

npm -g list

还有两个点你得注意下:
生的js文件中需要改成:
“use strict”;

var $protobuf = protobuf;(原本这里是require(‘xxx’))

然后生成d.ts文件要改
import * as $protobuf from “…/…/…/index”;
这里的index是protobuf.js的d.ts文件

±- protobufjs@6.8.8
| ±- @protobufjs/aspromise@1.1.2
| ±- @protobufjs/base64@1.1.2
| ±- @protobufjs/codegen@2.0.4
| ±- @protobufjs/eventemitter@1.1.0
| ±- @protobufjs/fetch@1.1.0
| | ±- @protobufjs/aspromise@1.1.2 deduped
| | -- @protobufjs/inquire@1.1.0 deduped | +-- @protobufjs/float@1.0.2 | +-- @protobufjs/inquire@1.1.0 | +-- @protobufjs/path@1.1.2 | +-- @protobufjs/pool@1.1.0 | +-- @protobufjs/utf8@1.1.0 | +-- @types/long@4.0.1 | +-- @types/node@10.17.17 | – long@4.0.0
这边是我本地的第三方库引用的

之前有尝试var $protobuf = protobuf;但是编辑器报错 我就直接var $protobuf = window.protobuf;也吧protobuf.js那边改成了
window.protobuf。

protobuf.js也要转换成d.ts吗?

不是转···是库里面自带有这个文件···或者从typing中去下载这个库的d.ts文件

protobuf.js 这个文件你导入为插件,勾选所有选项,允许编译器使用就不会报错。我用的时候是没有加window的···

pb.zip (74.9 KB)

这个是我用的protobuf.js和对应的d.ts文件。
protobuf.js这个文件你放在和你编译出来的js一个目录。
index.d.ts放到工程的根目录。

我把你给的这个protobuf.js还有index.d.ts替换了之后 取验证了一下 发现还是不行


这个是我写的测试例子
Player.proto转换的Player.d.ts 我打印出 grace还是undefined,你看是我这边写的方式错了吗?

你好。

Player.js 中有

root.grace = /**/;
// 注意它这里是导出了 root 而不是 grace
export { root as default };

因此,应当以这样的方式导入变量 grace

import root from './proto/Player';
const { grace } = root; // 等价于 const grace = root.grace;

这样写可以确保运行时不会报错。但在 IDE 中会有类型错误。

这是因为 pbts 生成的 Player.d.ts 类型文件并不匹配 Player.js 的内容,因此我们需要稍作修改:

// @ts-ignore
import root from './proto/Player';
const grace = root.grace as unknown as typeof import('./proto/Player').grace;

其中,添加 // @ts-ignore 是因为 import root 这一行的错误需要忽略。

1赞