Skip to content

Instantly share code, notes, and snippets.

@shrinktofit
Created January 22, 2021 10:00
Show Gist options
  • Save shrinktofit/2dcb492ba9dc763bdb51e133bd38b0dc to your computer and use it in GitHub Desktop.
Save shrinktofit/2dcb492ba9dc763bdb51e133bd38b0dc to your computer and use it in GitHub Desktop.
protobuf 最佳实践

pbjs

执行以下命令生成协议 .js 文件:

pbjs --target static-module --wrap commonjs --out <.js 输出路径> <.proto 输入路径,可为通配符>

pbts

执行以下命令生成协议 .d.ts 文件:

pbts --main --out <.d.ts 输出路径> <.js 输入路径>

编辑 .d.ts

需要适配一下 .d.ts 的内容。执行以下 node 代码:

const fs = require('fs');
const ps = require('path');
const file = '<.d.ts文件路径>';
const original = fs.readFileSync(file, { encoding: 'utf8' });
fs.writeFileSync(file, `
namespace protos {
    ${original}
}
export default protos;
`);

其中 protos 可为任意名称。

使用协议文件

import protos from "<到 .js 的路径,需要扩展名>";

protos. // 这里会有自动提示
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment