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

在Google Cloud Functions中使用pnpm工作区共享包时遇TypeScript错误

解决pnpm Monorepo中Google Cloud Functions无法导入共享Database包的ES模块目录问题

问题根源

Node.js的ES模块解析规则要求导入路径必须是带完整扩展名的文件路径,你的共享database包编译后生成了目录导入(比如import './schema')。NextJS内部有额外的模块解析逻辑可以处理这类目录导入,但Google Cloud Functions严格遵循Node.js原生ES模块规则,因此抛出ERR_UNSUPPORTED_DIR_IMPORT错误。

干净解决方案(保持TypeScript集成)

方案1:配置TypeScript自动生成带扩展名的导入路径

修改共享database包的tsconfig.json,启用Node.js兼容的模块解析规则,让TypeScript编译时自动添加.js扩展名:

{
  "compilerOptions": {
    "module": "ESNext",
    "moduleResolution": "NodeNext",
    "resolveJsonModule": true,
    "outDir": "./dist",
    "rootDir": "./src",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true,
    "strict": true,
    "skipLibCheck": true,
    // 关键配置:确保编译后生成带扩展名的导入
    "moduleSuffixes": [".js", ".ts"],
    "allowImportingTsExtensions": false
  },
  "include": ["src/**/*"],
  "exclude": ["node_modules", "dist"]
}

同时确保database包的package.json声明为ES模块:

{
  "name": "@repo/database",
  "type": "module",
  "main": "./dist/index.js",
  "types": "./dist/index.d.ts",
  "scripts": {
    "build": "tsc"
  }
}

重新构建database包后,编译后的dist/index.js会将目录导入(如./schema)替换为完整的文件路径(如./schema/index.js),符合Node.js ES模块要求。

方案2:显式导出Schema模块避免目录导入

在database包的src/index.ts中直接导出schema目录的所有内容,这样下游的Cloud Functions无需直接导入schema目录:

// packages/database/src/index.ts
export * from './schema/index.ts';

之后在Cloud Functions中直接从@repo/database导入所需的schema类型或函数即可,彻底规避目录导入问题。

方案3:启用Node.js实验性目录导入支持(不推荐)

如果上述方案无法快速落地,可以临时使用Node.js的实验性特性来支持目录导入,但注意这是不稳定特性,可能在后续版本中变更:
修改Cloud Functions的启动脚本,添加--experimental-specifier-resolution=node参数:

{
  "scripts": {
    "start": "node --experimental-specifier-resolution=node node_modules/@google-cloud/functions-framework --target=handler"
  }
}

验证步骤

  1. 执行pnpm --filter @repo/database build重新构建共享包
  2. 运行pnpm run start:serverless启动Cloud Functions
  3. 检查packages/database/dist/index.js中的导入语句是否已转为带.js扩展名的完整路径

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 21:46:02