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

如何在Firebase Functions中运行PostgreSQL并解决import语法报错

解决方案

报错根因为TypeORM默认加载了entity目录下的原始TS文件,Firebase Functions运行时加载的是编译后的CommonJS格式JS代码,Node.js在CommonJS模块上下文下无法识别ES模块的import语法,因此抛出该错误。你可以按以下步骤修改:

步骤1:修改TypeORM配置的实体加载路径

找到你的ormconfig.json配置文件,或是写在createConnection参数里的TypeORM初始化配置,将实体路径从匹配TS文件改为匹配编译后的JS文件,示例配置修改如下:

{
  // 其他配置保持不变
  "entities": [
    // 替换掉原来的 "src/entity/**/*.ts"
    "lib/entity/**/*.js"
  ],
  "migrations": [
    "lib/migration/**/*.js"
  ],
  "subscribers": [
    "lib/subscriber/**/*.js"
  ]
}

注意:如果你的TS编译输出目录不是lib,要改成你实际的输出目录,比如dist

步骤2:确认编译配置符合要求

检查tsconfig.json的compilerOptions下要设置"module": "CommonJS",保证TS编译输出的是CommonJS格式代码:

{
  "compilerOptions": {
    "module": "CommonJS",
    "target": "ES2017",
    "outDir": "lib",
    // 保留原有装饰器相关配置
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true
  }
}

同时不要在函数目录的package.json里添加"type": "module"配置,Firebase Functions默认兼容CommonJS模块格式,添加该配置会触发其他兼容问题。

步骤3:重新编译后启动服务

先执行npm run build把TS代码全量编译成JS输出到目标目录,再执行firebase serve --only functions即可正常运行。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 03:27:03