bufbuild / protobuf-es

Protocol Buffers for ECMAScript. The only JavaScript Protobuf library that is fully-compliant with Protobuf conformance tests.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Feature request: Make opportunity to generate all in one file

hegemonies opened this issue · comments

Hello!

protobuf-es is an excellent tool, I like it. But I would like to have the opportunity to generate all protobuf contracts to one index.js (or .ts) like in pbjs (https://www.npmjs.com/package/pbjs).

Because importing a lot of objects is not comfortable.

image (2)

Hey @hegemonies, protobuf.js uses namespaces to avoid name clashes in generated code.

For example, for the following proto file:

// google/protobuf/test_messages_proto3.proto
syntax = "proto3";
package protobuf_test_messages.proto3;
message TestAllTypesProto3 {}

It generates:

// protos_pb.d.ts
export namespace protobuf_test_messages {
    namespace proto3 {
        class TestAllTypesProto3 implements ITestAllTypesProto3 {
        }
    }
}

But namespaces have drawbacks. Let's take a look at the generated code is used:

import * as protos from "./gen/protos_pb.js";
const { TestAllTypesProto2 } = protos.protobuf_test_messages.proto2;
const { TestAllTypesProto3 } = protos.protobuf_test_messages.proto3;

Compare this with protobuf-es generated code:

import { TestAllTypesProto3 } from "./gen/google/protobuf/test_messages_proto3_pb.js";
import { TestAllTypesProto2 } from "./gen/google/protobuf/test_messages_proto2_pb.js";

This is much more idiomatic, works with type-only imports, and does not impede tree-shaking. It's a real-world example taken from here.

Namespaces will not be removed from the language, but ECMAScript modules have mostly replaced the need for them. Here is Anders Hejlsberg - core developer of TypeScript - on the topic: https://youtu.be/tXK50czRbdA?t=990

I hope you understand that it seems like a step backward to us to add support for namespaces in protoc-gen-es.

Of course there are still legit use cases for namespaces. It should be fairly straight-forward to create a plugin that generates a single file that provides all types from a set of proto files in a namespace tree. I think we should leave this issue open until we have an example for such a plugin.

@timostamm hey!

Thank you a lot for your quick and great answer!

I got it and I will close the issue.