N-M*_*Man 251 javascript node.js node-fetch discord.js hypixel-api
我正在尝试制作一个Discord机器人,它只会显示是否有人在线玩游戏。
然而我不断收到这样的消息:
[ERR_REQUIRE_ESM]:不支持 ES 模块的 require()。相反,将index.js in... 的 require 更改为动态 import(),该动态 import() 在所有 CommonJS 模块中都可用。
这是我的代码:
    module.exports = {
        name: 'username',
        description: "this is the username command",
        async execute(message, args) {
            const fetch = require('node-fetch');
            if (args.length !== 1) {
                return message.channel.send("invalid username wtf")
            }
            const ign = args[0]
            if (ign.length > 16 || ign.length < 3) {
                return message.channel.send("invalid username wtf")
            }
            const uuid = await fetch(`https://api.mojang.com/users/profiles/minecraft/${ign}`).then(data => data.json()).then(data => data.id).catch(err => message.channel.send("error wtf"));
            const onlineInfo = await fetch(`https://api.hypixel.net/status?key=${john}&uuid=${uuid}`).then(data => data.json());
            if (uuid.length !== 32) {
                return;
            }
            if (onlineinfo.success) {
                if (onlineinfo.session.online) {
                    message.channel.send("they are online")
                }
                else {
                    message.channel.send("they are offline")
                }
            }
            else {
                message.channel.send("hypixel api bad wtf")
            }
        }
    }
这是我的package.json文件:
{
    "name": "discordbot",
    "version": "1.0.0",
    "main": "main.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "node main.js"
    },
    "author": "",
    "license": "ISC",
    "description": "",
    "dependencies": {
        "discord.js": "^13.0.1",
        "node-fetch": "^3.0.0"
    }
}
小智 94
最新node-fetch版本不使用require()语法来导入包。您需要转到您的package.json并输入
 { 
   "type": "module",
 }
使用import语法和 import node-fetch,但是您不能用于require任何其他包。您只需要使用import语句即可。
或者您可以使用其他包,例如Got或Axios,可以通过require()语法导入。
N-M*_*Man 79
我想到了。我只好降级node-fetch到2.6.6,因为更高版本只使用ESM,这导致了很多错误。
iam*_*eel 40
node-fetchv3 最近停止支持require导入方式,转而支持 ES 模块。您现在需要使用 ESM 导入,例如:
import fetch from "node-fetch";
在你的文件的顶部。