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

JS如何导入函数?Node.js Discord机器人模块导入报错解决

问题修复方案

你遇到的模块导入报错以及后续会触发的运行错误,由3个核心写法问题导致,按以下步骤修复即可:

核心错误点

  • 导出语法错误:help.js中写的module.exports()是直接执行函数,并非导出模块内容,导致index.js引入时拿不到定义的help方法
  • 路径匹配错误:./commands/help.js是相对路径,必须保证commands文件夹和index.js在同一项目层级,否则会直接触发module not found报错
  • 依赖与参数缺失:help.js中没有引入discord.js依赖,同时help函数没有接收message入参,就算导入成功运行也会报变量未定义错误

正确目录结构

首先确认你的项目文件层级符合以下结构:

项目根目录/
├── index.js
├── node_modules/
├── package.json
└── commands/
    └── help.js

修复后代码

commands/help.js

// 引入discord.js依赖
const Discord = require("discord.js");

function help(message) {
    const embed = new Discord.MessageEmbed()
        .setColor("#0099ff")
        .setTitle("Commandes du serveur")
        .addField("&help", "Commandes du bot")
        .addField("&youtube", "Lien vers la chaîne YouTube d'ANGI49")
        .addField("&twitch", "Lien vers la chaîne Twitch d'ANGI49")
        .setFooter("Bot développé par ANGI498045 et ywalt.js")

    message.reply({ embeds: [embed] });
}

// 正确导出模块内容
module.exports = { help };

index.js

// 先确保已经执行npm install discord.js安装依赖
const { Client, Intents } = require("discord.js");
const helpCommand = require("./commands/help.js");

const client = new Client({
    intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES]
});

// 监听消息事件触发命令
client.on("messageCreate", (message) => {
    if (message.author.bot) return;
    if (message.content.trim() === "&help") {
        // 调用命令时传入message对象
        helpCommand.help(message);
    }
});

// 替换为你自己的机器人Token
client.login("你的机器人Token");

额外排查项

  • 执行npm ls discord.js确认依赖已正确安装,未安装的话先在项目根目录运行npm install discord.js
  • 注意文件名大小写:Linux/macOS系统对文件名大小写敏感,Help.js和help.js会被识别为两个不同文件
  • 如果你安装的是discord.js v14版本,需要将Discord.MessageEmbed替换为Discord.EmbedBuilder,同时去Discord开发者后台开启Message Content Intent权限,否则机器人无法接收普通消息

内容的提问来源于stack exchange,提问作者ywalt.js

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 05:54:16