proto-codegen
v1.1.0
Published
Generate TypeScript types and HTTP clients from Proto files
Maintainers
Readme
Proto Codegen
从 Protocol Buffer 文件生成 TypeScript 类型与 HTTP 客户端。
它做什么
Proto Codegen 读取 .proto 文件,输出 TypeScript 类型定义和类型化的 HTTP 客户端类。你写好 proto,运行一条命令,前端就拿到完整的类型化 API 层,不用手写请求代码。
类型层使用 ts-proto,客户端层读取 google.api.http 注解,支持 GET、POST、PUT、DELETE、PATCH。
为什么用它
- 类型安全。编译器在运行前就能拦住错误的参数和响应结构。
- 告别脱节。proto 文件是前后端契约的唯一来源。
- 响应解包。泛型客户端自动解包
{ code, data, message }之类的业务响应包装,代码直接操作内部类型。 - 内置 npm 发布与本地链接。带版本管理的包发布,或通过 watch 模式链接到前端项目。
- 可配置。用 JSON 文件或 CLI 参数驱动一切。
快速开始
安装:
npm install -g proto-codegen创建 proto-codegen.config.json:
{
"input": { "protoDir": "./proto" },
"output": { "dir": "./generated" },
"generation": { "generateTypes": true, "generateClients": true }
}添加带 HTTP 注解的 .proto 文件:
syntax = "proto3";
package example;
message GetUserRequest { string user_id = 1; }
message GetUserResponse { string id = 1; string name = 2; }
service UserService {
rpc GetUser(GetUserRequest) returns (GetUserResponse) {
option (google.api.http) = { get: "/api/v1/users/{user_id}" };
}
}生成:
proto-codegen generate然后在前端调用。生成器还会输出一个 HttpClient 接口(在 generated/clients/http-client.ts),用项目里现成的 HTTP 库(fetch、axios 等)实现它一次,所有生成的客户端就能用了:
import { HttpClient } from './generated/clients/http-client';
// 用你的 HTTP 库实现这个生成的接口——只需一次
class MyHttpClient implements HttpClient {
async get<T>(url: string, params?: any): Promise<T> {
const res = await fetch(url + '?' + new URLSearchParams(params));
return res.json();
}
// post、put、delete、patch...
}然后创建客户端调用——参数和返回值的类型都从 proto 自动推断:
import { UserServiceClient } from './generated/clients/user-client';
const userService = new UserServiceClient(new MyHttpClient());
const user = await userService.getUser({ userId: '123' }); // 类型是 GetUserResponse需要解包 { code, data, message } 之类的响应包装,或加路径前缀?见使用指南。
文档
完整文档(配置参考、CLI 命令、使用生成代码)都在文档站里。也可以在浏览器里直接试用,不用安装。
开发
pnpm install
pnpm build # 构建 CLI
pnpm docs:dev # 文档站开发服务器
pnpm docs:build # 构建文档站许可证
MIT
贡献
欢迎提交 Issue 和 Pull Request。
