Node.js在同一文件夹中需要多个文件

I'm building a discord bot with node.js for my server and I have a bunch of commands for the bot. Each command is in a different file so I have a lot of const cmd = require("../commands/cmd.js");

const kick = require("../commands/kick");
const info = require("../commands/info"); 
const cooldown = require("../commands/cooldown");
const help = require("../commands/help");

有没有更简单的方法可以做到这一点?

评论
  • equia
    equia 回复

    Inside folder commands put a file called index.js.

    Each time you implement new commands in new file, require that file in index.js and then add it to the exports of it. For example index.js would be:

    const kick = require('./kick');
    const info = require('./info');
    
    module.exports = {
      kick: kick,
      info: info
    }
    

    然后从任何文件夹中都可以在一行中要求多个命令,如下所示:

    const { kick, info } = require('../commands');
    
  • wrerum
    wrerum 回复

    而是从一个文件导出对象?

    const kick = require("../commands/kick");
    const info = require("../commands/info"); 
    const cooldown = require("../commands/cooldown");
    const help = require("../commands/help");
    
    const commands = {
      kick,
      info,
      ...
    }
    
    module.exports = commands;
    

    然后:

    const commands = require('mycommands')
    
    commands.kick()
    
  • xipsam
    xipsam 回复

    Create index.js file inside the command folder and then you can export an object like this.

    const kick = require("../commands/kick");
    const info = require("../commands/info"); 
    const cooldown = require("../commands/cooldown");
    const help = require("../commands/help");
    
    const command = {
      kick,
      info,
      cooldown,
      help
    };
    
    module.exports = command;
    

    您可以像这样导入和使用它:

    const {kick, info} = require('./commands');