協議緩衝區 - 在 TypeScript 中使用 `google.type.Date` 並執行 `buf generate` 時,變成相對匯入
當我在一個包含 google/type/date.proto 的文件上運行 buf generate 時,生成了一個包含相對路徑的 pb 文件。然而,沒有具有指定路徑的文件。語言是 TypeScript。
// a part of the generated code
import type { BinaryReadOptions, FieldList, JsonReadOptions, JsonValue, PartialMessage, PlainMessage } from "@bufbuild/protobuf";
import { Message, proto3 } from "@bufbuild/protobuf";
import { Date } from "../google/type/date_pb";
我原本以為它會引用輸出到 node_modules 的檔案(在 node_modules 中沒有與 google.type 相關的檔案)。我該如何擺脫相對路徑?
使用的文件如下。
protos/sample/sample.proto 是:
syntax = "proto3";
package sample;
import "google/protobuf/empty.proto";
import "google/type/date.proto";
message Sample {
google.type.Date start_date = 1;
}
service SampleService {
rpc Initialize(google.protobuf.Empty) returns (Sample);
}
buf.yaml 是:
version: v2
modules:
- path: protos
lint:
use:
- DEFAULT
breaking:
use:
- FILE
deps:
- buf.build/googleapis/googleapis:f0e53af8f2fc4556b94f482688b57223
buf.gen.yaml 是:
version: v2
managed:
enabled: true
disable:
- module: buf.build/googleapis/googleapis
plugins:
- remote: buf.build/connectrpc/es:v1.4.0
opt:
- target=ts
- import_extension=none
out: src/gen
- remote: buf.build/bufbuild/es
opt:
- target=ts
- import_extension=none
out: src/gen
檔案結構與指令:
tree
.
├── protos
│ └── sample
│ └── sample.proto
├── buf.gen.yaml
└── buf.yaml
buf dep update
buf generate
答案#1
我找到的唯一解決方法是向構建過程中添加幾個「手動」(即未由 buf 處理的)步驟:
buf export buf.build/googleapis/googleapis --output ./tmp
protoc --js_out=import_style=commonjs,binary:gen/js -I ./tmp google/type/latlng.proto
