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

Firebase Cloud Functions(TypeScript)动态导入错误求助

解决Cloud Functions中chatgpt模块的ESM/CommonJS兼容问题

问题原因

你使用的chatgpt包是纯ESM模块,但你的Cloud Functions代码被编译成了CommonJS格式,Node.js不允许在CommonJS模块里用require()加载ESM模块,因此触发了该报错。

解决方案一:使用动态导入(快速适配现有CommonJS配置)

按照报错提示,把原来的require改为异步的import(),注意要在async函数内执行:

原来的错误写法:

const { ChatGPTAPI } = require('chatgpt');

exports.chatGptFunction = functions.https.onRequest((req, res) => {
  // 初始化API并处理请求
});

修改后:

exports.chatGptFunction = functions.https.onRequest(async (req, res) => {
  // 动态导入chatgpt模块
  const { ChatGPTAPI } = await import('chatgpt');
  const api = new ChatGPTAPI({ apiKey: process.env.OPENAI_API_KEY });
  
  // 后续业务逻辑示例
  const response = await api.sendMessage('Hello World');
  res.send(response.text);
});
  • 必须将触发器函数改为async,因为import()是异步操作
  • 所有依赖chatgpt的逻辑都要放在await import()之后执行

解决方案二:切换Cloud Functions为ESM模式(长期适配)

Node.js 18原生支持ESM,可以直接把整个Functions项目改成ESM格式,彻底避免模块兼容问题:

  1. 修改tsconfig.json配置:
{
  "compilerOptions": {
    "module": "ESNext",
    "noImplicitReturns": true,
    "noUnusedLocals": true,
    "outDir": "lib",
    "sourceMap": true,
    "strict": true,
    "target": "ES2020",
    "esModuleInterop": true,
    "moduleResolution": "NodeNext"
  },
  "compileOnSave": true,
  "include": [
    "src"
  ]
}
  1. 在functions/package.json中添加"type": "module":
{
  "name": "functions",
  "type": "module",
  "scripts": {
    // 原有脚本保持不变
  },
  // 其他依赖配置...
}
  1. 将代码中的require全部替换为ESM的import语法:
import { ChatGPTAPI } from 'chatgpt';
import * as functions from 'firebase-functions';

exports.chatGptFunction = functions.https.onRequest(async (req, res) => {
  const api = new ChatGPTAPI({ apiKey: process.env.OPENAI_API_KEY });
  const response = await api.sendMessage('Hello World');
  res.send(response.text);
});
  1. 注意事项:
  • 导入本地文件时必须添加完整扩展名,比如import './utils.js'(不能省略.js)
  • Firebase CLI 11.25.1已支持ESM格式的Functions,无需额外升级

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 19:52:37