如何在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:
- 在
functions目录的package.json中添加:"type": "module" - 修改
tsconfig.json的相关配置:{ "compilerOptions": { "module": "ESNext", "moduleResolution": "node16", "target": "ES2020", "outDir": "./lib", "rootDir": "./src" } } - 确保你的Firebase CLI版本在v10.0.0以上(支持ESM函数):
npm install -g firebase-tools@latest - 重新编译并启动模拟器。
注意:这种方式需要确认你的Cloud Functions运行时环境支持ESM(Node.js 14+版本已支持,但部分旧版本可能有兼容问题)。
内容的提问来源于stack exchange,提问作者Ibrahim Ali
相关产品推荐
相关产品推荐

