错误[ ERR_REQUIRE_ESM ] : ES 模块的 request()不支持

我正在尝试制作一个 不和谐机器人,只是说,如果有人在线上的游戏。

然而,我一直收到这样的信息:

[ ERR _ REQUIRE _ ESM ] : 不支持 ES 模块的 request ()。相反,将... 中 index.js 的要求更改为所有 CommonJS 模块中都可用的动态 import ()。

这是我的暗号:

    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")
}
}
}

这是我的 包裹 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"
}
}
299556 次浏览

node-fetch v3最近停止了对 require导入方式的支持,转而支持 ES 模块。你现在需要使用 ESM 导入,比如:

import fetch from "node-fetch";

在你档案的最上面。

node-fetch的最新版本不使用 require()语法导入包。你需要去你的 package.json和类型

 {
"type": "module",
}

使用 import语法并导入 node-fetch,但是您不能对任何其他包使用 require。您只需使用 import语句。

或者可以使用其他包,如 明白Axios,它们可以通过 require()语法导入。

我想通了。我不得不把 node-fetch降级到2.6.6,因为更高的版本只使用 ESM,这导致了很多错误。