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

基于WOK教程开发discord.js机器人报feature is not a function错误求助

DJS机器人load-features模块TypeError排查解决方案

错误根因

TypeError: feature is not a function 错误本质是require()加载的目标文件导出的内容不是可执行函数,与你提供的load-features.js核心逻辑无关,问题出在被加载的其他feature文件、目录内的非预期文件,或者模块解析规则变动上。

排查步骤

  • 第一步:定位出错的具体文件
    在const feature = require(path.join(__dirname, dir, file));后新增一行日志:
    console.log(`Loaded file ${file}, export type: ${typeof feature}`);
    
    运行代码后,找到日志中export type不为function的文件,直接锁定问题目标。
  • 第二步:检查目标文件导出规则
    确认锁定的文件符合CommonJS导出要求:
    • 必须使用module.exports = (client) => { /* 逻辑 */ }导出函数,不能出现拼写错误如module.export(少写末尾s)
    • 如果文件使用了ES模块语法export default导出,需要修改引入逻辑为const feature = require(...).default,或者移除文件内的ES模块导出写法
    • 排查最近是否新增了feature文件、或修改过已有feature文件的导出语句
  • 第三步:过滤非JS文件
    目录内如果存在.md、.json、.log等非JS文件,被require加载后导出内容必然不是函数,修改load-features的判断逻辑,仅加载JS文件:
    将原判断条件else if (file !== "load-features.js")修改为:
    else if (file.endsWith('.js') && file !== "load-features.js")
    
  • 第四步:检查模块环境变动
    如果最近修改过package.json、升级过Node版本或依赖:
    • 检查package.json中是否新增了"type": "module"配置,该配置会将项目切换为ES模块环境,CommonJS的require逻辑会发生变化,要么移除该配置,要么将所有模块改为ES模块写法使用import/export
    • 删除node_modules目录、package-lock.json或yarn.lock文件,重新执行依赖安装后再运行,排除依赖缓存异常问题

优化后代码

可以直接替换原load-features.js代码,增加容错逻辑,避免单文件错误导致整个项目崩溃:

const path = require("path");
const fs = require("fs");

module.exports = (client) => {
    const readFeatures = (dir) => {
        const files = fs.readdirSync(path.join(__dirname, dir));
        for (const file of files) {
            const fullPath = path.join(__dirname, dir, file);
            const stat = fs.lstatSync(fullPath);
            if (stat.isDirectory()) {
                readFeatures(path.join(dir, file));
            } else if (file.endsWith('.js') && file !== "load-features.js") {
                const feature = require(fullPath);
                if (typeof feature === 'function') {
                    console.log(`Enabling feature "${file}"`);
                    feature(client);
                } else {
                    console.warn(`Skipping invalid feature file: ${file} (export is not a function)`);
                }
            }
        }
    };

    readFeatures(".");
};

内容的提问来源于stack exchange,提问作者PrezOfTheUnitedIdiots

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 08:00:01