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

如何在Google Cloud Functions中导入特定方法?启动模拟器遇ESM错误

解决Google Cloud Functions导入lodash-es时的ESM兼容性错误

错误原因

你遇到的ERR_REQUIRE_ESM错误,是因为lodash-es是纯ES模块(ESM),而Google Cloud Functions默认使用CommonJS模块系统。你的TypeScript代码编译后生成的lib/index.js是CommonJS格式,用require()加载ESM模块会被Node.js禁止。

解决方案

方案1:改用CommonJS版本的lodash(推荐)

这是最简便且兼容性最好的方法:

  • 卸载lodash-es:
    npm uninstall lodash-es
    
  • 安装CommonJS版本的lodash:
    npm install lodash
    
  • 修改index.ts中的导入语句:
    import * as functions from "firebase-functions";
    import { includes } from "lodash"; // 替换lodash-es为lodash
    
    export const isFruit = functions.https.onCall((_, __) => includes(["apple", "orange"], "apple"));
    
  • 重新编译并启动模拟器:
    npm run build
    firebase emulators:start
    

方案2:配置项目为ESM格式(进阶)

如果你坚持使用lodash-es,需要将Cloud Functions项目配置为ESM:

  1. 在functions目录的package.json中添加:
    "type": "module"
    
  2. 修改tsconfig.json的相关配置:
    {
      "compilerOptions": {
        "module": "ESNext",
        "moduleResolution": "node16",
        "target": "ES2020",
        "outDir": "./lib",
        "rootDir": "./src"
      }
    }
    
  3. 确保你的Firebase CLI版本在v10.0.0以上(支持ESM函数):
    npm install -g firebase-tools@latest
    
  4. 重新编译并启动模拟器。

注意:这种方式需要确认你的Cloud Functions运行时环境支持ESM(Node.js 14+版本已支持,但部分旧版本可能有兼容问题)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 15:48:05