使用require导入chatgpt包遇ERR_REQUIRE_ESM错误,多种方案无效
解决ERR_REQUIRE_ESM错误及Discord机器人无法上线问题
问题根源
chatgpt包是纯ESM模块,当你在package.json中添加"type": "module"后,所有.js文件默认采用ESM语法,不能再使用CommonJS的require()和module.exports,否则会引发语法冲突,导致机器人无法正常启动。
解决方案
将代码中所有CommonJS语法替换为ESM语法,具体修改如下:
修改后的完整代码
// <--- Discord Stuff ---> import Discord from 'discord.js'; const client = new Discord.Client( { intents: 32767 }, { partials: ["MESSAGE", "CHANNEL", "REACTION", "GUILD_MEMBER"] } ); export default client; // <--- Discord Stuff ---> // Other Stuff import { ChatGPTAPI } from 'chatgpt'; import dotenv from 'dotenv'; dotenv.config(); const api = new ChatGPTAPI({ apiKey: process.env.OPENAI_API_KEY }) // Other Stuff client.on("messageCreate", async (message) => { if (message.channel.id === '1063790255880286269' && !message.author.bot) { try { const res = await api.sendMessage(message.content); await message.channel.send({ content: `<@${message.author.id}> ${res.text}` }); } catch (err) { console.error('ChatGPT请求失败:', err); await message.channel.send('抱歉,暂时无法处理你的请求,请稍后再试。'); } } }) process.on("unhandledRejection", (reason, p) => { console.log(" [antiCrash] :: Unhandled Rejection/Catch"); console.log(reason, p); }); process.on("uncaughtException", (err, origin) => { console.log(" [antiCrash] :: Uncaught Exception/Catch"); console.log(err, origin); }); process.on("uncaughtExceptionMonitor", (err, origin) => { console.log(" [antiCrash] :: Uncaught Exception/Catch (MONITOR)"); console.log(err, origin); }); client.login(process.env.DISCORD_TOKEN);
关键修改点说明
- 把
const Discord = require("discord.js")替换为import Discord from 'discord.js' - 把
module.exports = client替换为export default client - 把
const ChatGPTAPI = require('chatgpt')替换为import { ChatGPTAPI } from 'chatgpt' - 把
require("dotenv").config()替换为import dotenv from 'dotenv'+dotenv.config() - 给ChatGPT请求添加
try/catch捕获异常,避免API调用失败导致机器人崩溃
额外注意事项
- 确保Node.js版本在16.14.0及以上,低版本对ESM支持不完善
- 无需手动指定
node-fetch版本,chatgpt包会自动处理依赖,避免版本冲突
内容的提问来源于stack exchange,提问作者Pooyan
相关产品推荐
相关产品推荐

