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

如何修复Replit上Discord.js v14的TypeError: require(...) is not a function错误

问题描述

我在Replit上托管了一个基于Discord.js v14的命令处理器Bot,三周后打开Replit时出现了TypeError: require(...) is not a function错误,急需修复以便将Bot上架top.gg。相关错误栈和代码如下:

错误栈

TypeError: require(...) is not a function
    at /home/runner/uniquegamer204/index.js:28:35
    at Array.forEach (<anonymous>)
    at Object.<anonymous> (/home/runner/uniquegamer204/index.js:27:30)
    at Module._compile (node:internal/modules/cjs/loader:1101:14)

核心代码

const { Client, GatewayIntentBits, Partials, Collection } = require('discord.js');
const client = new Client({
    intents: [
        GatewayIntentBits.Guilds, 
        GatewayIntentBits.GuildMessages, 
        GatewayIntentBits.GuildPresences, 
        GatewayIntentBits.GuildMessageReactions, 
        GatewayIntentBits.DirectMessages,
        GatewayIntentBits.MessageContent
    ], 
    partials: [Partials.Channel, Partials.Message, Partials.User, Partials.GuildMember, Partials.Reaction] 
});

const fs = require('fs');
const config = require('./config.json');

client.commands = new Collection()
client.aliases = new Collection()
client.slashCommands = new Collection();
client.buttons = new Collection();
client.prefix = config.prefix;

module.exports = client;


fs.readdirSync('./handlers').forEach((handler) => {
  require(`./handlers/${handler}`)(client)
});

client.login(process.env.TOKEN)
修复方案
  • 检查Handler文件导出格式:错误触发点是调用require('./handlers/${handler}')(client),说明至少有一个handler文件没有导出可执行函数。所有handler必须以函数形式导出,示例:
module.exports = (client) => {
  // 此处编写handler逻辑
};

若handler导出的是对象、字符串等非函数类型,调用()`就会抛出该错误。

  • 过滤Handler目录中的非JS文件:fs.readdirSync('./handlers')会读取目录下所有文件,若存在.json、.txt等非JS文件,require后返回的不是函数,调用()`会报错。修改代码只处理.js文件:
fs.readdirSync('./handlers')
  .filter(file => file.endsWith('.js'))
  .forEach((handler) => {
    require(`./handlers/${handler}`)(client)
  });
  • 修复Replit环境依赖问题:三周未启动项目,可能依赖包版本自动更新导致兼容问题。在package.json中锁定Discord.js的具体版本(如"discord.js": "^14.14.1"),然后执行npm install重新安装依赖。

  • 验证配置文件有效性:确认config.json是合法的JSON格式,避免因配置文件解析失败间接引发问题。

内容的提问来源于stack exchange,提问作者Mohammad Zohaib Ur Rahman

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 22:55:37