Discord.js命令部署失败:无法读取命令文件data属性
解决Discord.js部署命令时的TypeError: Cannot read properties of undefined (reading 'toJSON')
问题根源
从日志输出能看到,require('./commands/echo.js')返回空对象,说明命令模块没有正确导出data变量。Node.js的CommonJS模块默认不会暴露内部定义的变量,必须通过module.exports明确导出,部署脚本才能读取到command.data。
修复步骤
1. 修正命令文件(以ping.js为例)
在命令文件末尾添加导出语句,将data对象暴露给外部模块:
const { SlashCommandBuilder } = require('discord.js'); const data = new SlashCommandBuilder() .setName('ping') .setDescription('Replies with pong!'); // 关键:导出data对象 module.exports = { data };
注意:日志里提到的echo.js也需要做同样的修改,确保所有命令文件都正确导出data。
2. 可选:添加错误预防逻辑(增强脚本健壮性)
在部署脚本的循环中增加检查,避免因单个错误命令导致整个部署失败:
for (const file of commandFiles) { console.log(file) const command = require(`./commands/${file}`); // 检查是否存在合法的data对象 if (command?.data?.toJSON) { commands.push(command.data.toJSON()); } else { console.warn(`⚠️ 命令文件 ${file} 未正确导出符合要求的data对象,已跳过`); } }
验证
重新运行部署脚本,此时command.data应该能正确读取到SlashCommandBuilder实例,调用toJSON()也不会再报错。
内容的提问来源于stack exchange,提问作者user13524876
相关产品推荐
相关产品推荐

