Require in ES Module not working, despite createRequire

Viewed 39

I am currently working on a discord.js bot, that has its commands in seperate files.

The bot is an ES module.
While coding, I ran into a problem when using the require statement, because require obviously doesn't work in ES modules.

Then I remembered, that require() for ES modules worked for me in the past after inserting these two lines of code:

import { createRequire } from "module";
const require = createRequire(import.meta.url);

And when I use require() on any normal file like .json's it works fine, but for the code below it doesn't (main.js):

import Discord from "discord.js";
import fs from "fs";
import * as Botfuncs from "dcjs-botfuncs";

import { createRequire } from "module";
const require = createRequire(import.meta.url);

// here I create the client
const client = new Discord.Client({
  partials: ["MESSAGE", "CHANNEL", "REACTION"],
});
client.commands = new Discord.Collection();

const commandFiles = fs.readdirSync("./commands").filter((file) => file.endsWith(".js"));
  
// here I try setting the commands into a Map
commandFiles.forEach((file) => {
  const cmd = require(`./commands/${file}`);
  client.commands.set(cmd.name, cmd);
});

// ...

This is how one of the command files looks like:

const Discord = require('discord.js');
module.exports = {
    name: 'commandName',
    execute(message, arguments, client, prefix){ /* ... */ }
};

And this is the error-message I get:

Error [ERR_REQUIRE_ESM]: require() of ES Module D:\path\to\bot\command-name.js from D:\path\to\bot\main.js not supported. command-name.js is treated as an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which declares all .js files in that package scope as ES modules. Instead rename avatar.js to end in .cjs, change the requiring code to use dynamic import() which is available in all CommonJS modules, or change "type": "module" to "type": "commonjs" in D:\path\to\bot\package.json to treat all .js files as CommonJS (using .mjs for all ES modules instead).

If it helps, here is my package.json:

{
  "name": "ArcadeFlyer",
  "version": "1.0.0",
  "description": "Best description",
  "main": "main.js",
  "type": "module",
  "author": "phil_not_funny",
  "license": "ISC",
  "dependencies": {
    "dcjs-botfuncs": "^0.4.19",
    "discord.js": "^12.5.1"
  }
}

I have the suspicion, that the module.exports is the problem here, but is there any work-around to this problem?
I don't want to be manually importing every single command into my main.js

Any help is appreciated!
Thanks in advance.

0 Answers
Related