0

In my guild command file I have to require all files of the commands folder and save them as a variable in a FOR-Loop.

In ES5 it would look like that:

for (const file of commandFiles) {
   const command = require(`../commands/${file}`);
   commands.push(command.data.toJSON());
}

But I want to import everything with ES6 and the import statement. Is there a way to convert the code above to ES6-compatible code?

Baumistlustig
  • 43
  • 1
  • 4

3 Answers3

1

require(x) vs import x

Dynamic import() returns a promise, that's why you have to use await before it.

If the module exported as default, you should use const { default: command } = await import(x), if you want to use const command, use command.default instead of command later in the code.

for (const file of commandFiles) {
    const command = await import(`../commands/${file}`);
    commands.push(command.data.toJSON());
}
yes sir
  • 220
  • 2
  • 8
  • 1
    Your answer could be improved by adding more information on what the code does and how it helps the OP. – Tyler2P May 23 '22 at 17:27
0

Try using FS || FileSystem:

const fs = require("fs"); // Import the FileSystem

fs.readdirSync(`../commands`).forEach(file => {
  const command = require(`../commands/${file}`); // Saving the imported file as a constant
  // Do something with the "command" constant
});

Explaination:

  • First we import FileSystem || FS.
  • Then we use FS's "readdirSync()" function to get all the files from the "commands" directory.
  • As we get all the file names from the "commands" folder, we import each of them as "command" constant.
  • Now all the content of "file" is stored in the "command" constant.
  • Now everything is done and you can write your code.

If you have any other questions, related to this code, please feel free to ask me them in the comments.

Omen
  • 31
  • 7
-1

Try something like this:

  for (const file of commandFiles) {
        const command = require(`./commands/${file}`);
        client.commands.set(command.name, command);
    }
Floris
  • 69
  • 8
  • Thank you for your answer but I think you didn't get the question right. This code works perfectly fine with ES5 but I want to use ES6 imports. There I'll get an Error saying: `This file is being treated as an ES module because it has a '.js' file extension and ...` – Baumistlustig May 22 '22 at 19:21
  • Sorry, I don;t have any knowledge from that, But I googeld it! https://stackoverflow.com/questions/69099763/referenceerror-require-is-not-defined-in-es-module-scope-you-can-use-import-in – Floris May 22 '22 at 19:25
  • Thank you, but this doesn't help too because it just says I should use ES5 Syntax – Baumistlustig May 22 '22 at 19:27
  • Where did you get that `client.commands.set(command.name, command);` line from? – Bergi May 22 '22 at 20:33