You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用buf generate生成TypeScript代码时google.type.Date相对导入问题

解决buf generate生成TypeScript代码时的相对路径导入问题

执行buf generate后,生成的TypeScript代码中出现了无效的相对路径导入:

import { Date } from "../google/type/date_pb";

该路径下不存在对应文件,且无法从node_modules找到相关模块,需要调整配置消除这种无效相对路径。

问题根源

buf.gen.yaml中managed.disable排除了buf.build/googleapis/googleapis模块的托管模式,导致代码生成器无法为依赖的Google APIs proto文件生成正确的导入路径和对应的代码文件。

解决方案

  1. 修改buf.gen.yaml配置
    移除managed配置中对buf.build/googleapis/googleapis的禁用,让托管模式处理所有模块:
version: v2
managed:
  enabled: true
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
  1. 重新生成代码
    先清理旧的生成文件,再重新执行生成命令:
rm -rf src/gen
buf generate

效果验证

调整后,生成的代码中会自动创建src/gen/google/type/date_pb.ts文件,导入路径变为有效的同层级相对路径:

import { Date } from "./google/type/date_pb";

确保所有依赖的类型都能正确引用。

内容的提问来源于stack exchange,提问作者hirano00o

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 04:06:12