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

discord.js开发报Must use import to load ES Module错误如何修复

报错原因

你遇到的ERR_REQUIRE_ESM错误是由于你安装的node-fetch包版本≥3.0,该版本起node-fetch仅支持ES Module导入规范,不兼容你当前项目使用的CommonJS的require()导入语法。

解决方案

优先推荐改动最小的方案1:

  • 方案1:降级node-fetch到支持CommonJS的v2版本
    执行以下命令重新安装对应版本:
    npm uninstall node-fetch
    npm install node-fetch@2
    
    安装完成后无需修改现有代码,直接运行即可。
  • 方案2:保留高版本node-fetch,改用动态import加载
    删除roast.js中const fetch = require('node-fetch')这一行,将网络请求部分的代码修改为:
    import('node-fetch')
      .then(({default: fetch}) => fetch('http://evilinsult.com/generate_insult.php?lang=en&type=json'))
      .then(res => res.json())
      .then(json => {
          message.channel.send(json.insult)
      });
    
  • 方案3:将项目整体切换为ES Module规范
    1. 在项目根目录的package.json文件中添加配置:"type": "module"
    2. 将所有js文件中的require()导入语法替换为import语法,module.exports导出语法替换为export default语法
额外注意

你当前roast.js中存在语法错误:const mentionedMember = message.guild.mentions.member.first();应修改为const mentionedMember = message.mentions.members.first();,否则即使模块导入问题解决,调用命令时也会抛出找不到用户的错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 11:33:01