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

如何解决Error [ERR_REQUIRE_ESM]: require()加载ES Module不支持问题?

解决Discord机器人meme命令中got包的ESM引入错误

问题原因

你猜的没错,问题确实出在got包本身。从got v11版本开始,它就完全切换成了ES模块(ESM),不再支持CommonJS的require()语法引入,而你的代码是基于CommonJS写的(用require和module.exports),所以才会触发这个错误。

解决方案

方案1:降级到支持CommonJS的got版本

直接安装v10.x版本的got,这个版本还保留对CommonJS的支持:

npm install got@10

安装完成后,你的现有代码不需要任何修改,就能正常运行。

方案2:改用CommonJS兼容的HTTP库

如果不想降级,可以换成支持CommonJS的替代库,比如axios:

  1. 安装axios:
npm install axios
  1. 修改你的代码,替换got为axios:
const { EmbedBuilder } = require("discord.js");
const axios = require("axios");

module.exports = {
  name: "meme",
  description: "Shows an image of a meme!",
  run: async (client, message, args) => {
    axios.get("https://www.reddit.com/r/memes/random/.json")
      .then(response => {
        const [list] = response.data;
        const [post] = list.data.children;

        const memeUrl = `https://reddit.com${post.data.permalink}`;
        const memeImage = post.data.url;
        const memeTitle = post.data.title;
        const memeUpvotes = post.data.ups;
        const memeNumComments = post.data.num_comments;
        
        const memeEmbed = new EmbedBuilder()
           .setTitle(memeTitle)
           .setURL(memeUrl)
           .setColor("Random")
           .setImage(memeImage)
           .setFooter({ text: `👍 ${memeUpvotes} | 💬 ${memeNumComments}` });
        message.reply({ embeds: [memeEmbed] });
      })
      .catch(err => console.error(err));
  }
};

注意:axios会自动解析JSON响应,所以不需要手动调用JSON.parse()。

方案3:将你的项目转为ESM(不推荐新手)

如果想彻底切换到ESM,需要做以下修改:

  1. 在项目根目录的package.json中添加"type": "module":
{
  "type": "module"
}
  1. 将所有require()替换为import,module.exports替换为export default:
import { EmbedBuilder } from "discord.js";
import got from "got";

export default {
  name: "meme",
  description: "Shows an image of a meme!",
  run: async (client, message, args) => {
    const response = await got("https://www.reddit.com/r/memes/random/.json");
    const [list] = JSON.parse(response.body);
    const [post] = list.data.children;

    const memeUrl = `https://reddit.com${post.data.permalink}`;
    const memeImage = post.data.url;
    const memeTitle = post.data.title;
    const memeUpvotes = post.data.ups;
    const memeNumComments = post.data.num_comments;
    
    const memeEmbed = new EmbedBuilder()
       .setTitle(memeTitle)
       .setURL(memeUrl)
       .setColor("Random")
       .setImage(memeImage)
       .setFooter({ text: `👍 ${memeUpvotes} | 💬 ${memeNumComments}` });
    message.reply({ embeds: [memeEmbed] });
  }
};

不过这个方案需要你修改整个项目的模块语法,对新手来说可能比较麻烦,所以优先推荐前两个方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 10:36:28