Firebase Functions更新后出现ERR_REQUIRE_ESM错误求助
Firebase Functions 更新后出现 ERR_REQUIRE_ESM 错误排查
之前Firebase Functions运行正常,更新后出现Error [ERR_REQUIRE_ESM]错误,相关配置及报错信息如下:
package.json
{ "name": "functions", "scripts": { "lint": "eslint --ext .js,.ts .", "lint:fix": "eslint --fix --ext .js,.jsx .", "build": "tsc", "watch": "tsc --watch", "serve": "npm run build && firebase emulators:start --only functions", "shell": "npm run build && firebase functions:shell", "start": "npm run shell", "deploy": "firebase deploy --only functions", "logs": "firebase functions:log" }, "engines": { "node": "16" }, "main": "lib/index.js", "dependencies": { "@google-cloud/video-intelligence": "^4.1.1", "@sendgrid/mail": "^7.7.0", "agora-access-token": "^2.0.4", "camelcase-keys": "^8.0.2", "firebase-admin": "^11.2.1", "firebase-functions": "^4.0.2", "google-auth-library": "^8.7.0", "googleapis": "^109.0.1", "lodash": "^4.17.21", "node-apple-receipt-verify": "^1.12.1" }, "devDependencies": { "@types/node-apple-receipt-verify": "^1.7.1", "@typescript-eslint/eslint-plugin": "^5.42.1", "@typescript-eslint/parser": "^5.42.1", "eslint": "^8.27.0", "eslint-config-google": "^0.14.0", "eslint-plugin-import": "^2.26.0", "firebase-functions-test": "^3.0.0", "typescript": "^4.8.4" }, "private": true }
tsconfig.json
{ "compilerOptions": { "module": "commonjs", "noImplicitReturns": true, "noUnusedLocals": true, "outDir": "lib", "sourceMap": true, "strict": true, "target": "es2017", "resolveJsonModule": true, "esModuleInterop": true, "allowSyntheticDefaultImports": true }, "compileOnSave": true, "include": [ "src" ] }
原导入方式
import camelcaseKeys from "camelcase-keys";
报错信息
Error: Failed to load function definition from source: Failed to generate manifest from function source: Error [ERR_REQUIRE_ESM]: require() of ES Module C:\Users\xxx\AndroidStudioProjects\xxx\functions\node_modules\camelcase-keys\index.js from C:\Users\xxx\AndroidStudioProjects\xxx\functions\lib\app-store.purchase-handler.js not supported. Instead change the require of index.js in C:\Users\xxx\AndroidStudioProjects\xxx\functions\lib\app-store.purchase-handler.js to a dynamic import() which is available in all CommonJS modules.
解决方法
1. 降级 camelcase-keys 到 CommonJS 兼容版本
camelcase-keys v8.x 版本开始转为纯ESM包,而你的项目配置为CommonJS(tsconfig中module设为commonjs),直接降级到v7.x版本即可解决:
npm install camelcase-keys@7.0.2
降级后可继续使用原有的import语法。
2. 使用动态导入兼容ESM包
如果不想降级,可将静态导入改为动态import()(CommonJS模块支持该语法):
async function processPurchase() { const { default: camelcaseKeys } = await import("camelcase-keys"); // 在这里使用camelcaseKeys处理数据 }
注意动态导入是异步操作,需要在异步函数中执行。
3. 将项目迁移到 ESM 规范
若想长期使用ESM包,可彻底迁移项目:
- 修改
tsconfig.json的compilerOptions.module为ESNext或ES2020 - 在
package.json中添加"type": "module" - 调整所有导入/导出语法以符合ESM规范(比如替换
require为import,修改文件扩展名等) - 确认所有依赖包均支持ESM规范
内容的提问来源于stack exchange,提问作者Cenk YAGMUR
相关产品推荐
相关产品推荐

