Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

259
Visualizações
How to fix Must use import to load ES Module discord.js

I am working on a bot i made a roast command i am getting this error

internal/modules/cjs/loader.js:1089
      throw new ERR_REQUIRE_ESM(filename, parentPath, packageJsonPath);
      ^

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: C:\Users\acer\Documents\test\node_modules\node-fetch\src\index.js
require() of ES modules is not supported.
require() of C:\Users\acer\Documents\test\node_modules\node-fetch\src\index.js from C:\Users\acer\Documents\test\commands\roast.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from C:\Users\acer\Documents\test\node_modules\node-fetch\package.json.

←[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1089:13)←[39m
←[90m    at Module.load (internal/modules/cjs/loader.js:937:32)←[39m
←[90m    at Function.Module._load (internal/modules/cjs/loader.js:778:12)←[39m
←[90m    at Module.require (internal/modules/cjs/loader.js:961:19)←[39m
←[90m    at require (internal/modules/cjs/helpers.js:92:18)←[39m
    at Object.<anonymous> (C:\Users\acer\Documents\test\commands\roast.js:3:15)
←[90m    at Module._compile (internal/modules/cjs/loader.js:1072:14)←[39m
←[90m    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1101:10)←[39m
←[90m    at Module.load (internal/modules/cjs/loader.js:937:32)←[39m
←[90m    at Function.Module._load (internal/modules/cjs/loader.js:778:12)←[39m {
  code: ←[32m'ERR_REQUIRE_ESM'←[39m

this is my roast.js

const random = require("something-random-on-discord").Random
const oneLinerJoke = require('one-liner-joke');
const fetch = require('node-fetch')
const Discord = require('discord.js')
module.exports = {
    name : 'roast',
    description : 'roasts a user',
    
  async execute(message, args){
       if (!args[0]) return message.channel.send('Invalid Format')
       const mentionedMember = message.guild.mentions.member.first();
       if (!mentionedMember) return message.channel.send('User not found')
        let msg = await message.channel.send('Setting a roast...')

        fetch('http://evilinsult.com/generate_insult.php?lang=en&type=json')
            .then(res => res.json())
            .then(json => {
                message.channel.send(json.insult)
            });
    }

}

this is my main.js

// Import the discord.js module
const Discord = require('discord.js');
const fs = require('fs');
// Create an instance of a Discord client
const client = new Discord.Client();
client.commands = new Discord.Collection();
const commandFiles = fs.readdirSync('./commands').filter(file => file.endsWith('.js'));
const prefix = "$"

/**
 * The ready event is vital, it means that only _after_ this will your bot start reacting to information
 * received from Discord
 */
client.on('ready', () => {
  console.log('I am ready!');
});
 
client.on('message', message => {
  if (!message.content.startsWith(prefix) || message.author.bot) return;

  const args = message.content.slice(prefix.length).trim().split(/ +/);
  const command = args.shift().toLowerCase();


  if(command === 'pingg'){
    client.commands.get('pingg').execute(message, args);
  }
  if(command === 'roast'){
    client.commands.get('roast').execute(message, args);
  }




  if (!client.commands.has(command)) return;

  try {
      client.commands.get(command).execute(message, args);
  } catch (error) {
      console.error(error);
      message.reply('there was an error trying to execute that command!');
  }
});
 

commandFiles.forEach(file => {
  const command = file.split(/.js$/)[0];
  client.commands.set(command, require(`./commands/${file}`));
});



client.login('censored');
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

as the error states :

package.json contains "type": "module" which defines all .js files in that package scope as ES modules

you usually have 3 options:

  1. Try removing this line from package.json to use only requires in your code.
  2. or keep this line and use import statements instead of require statements everywhere in your app (ES6).
  3. rename your file to index.cjs, then require in allowed in this particular file, while you still must use import in others.

in your particular case, you are using node-fetch which is now esmodule only (since version 3). then the only solution available for you is to use import everywhere.

requires should become something like this:

import {Random} from 'something-random-on-discord';
import oneLinerJoke from 'one-liner-joke';
import fetch from 'node-fetch';
import Discord from 'discord.js';

EDIT: you can also remove node fetch or revert to branch v2 to keep using require.

over 4 years ago · Santiago Trujillo Relatório

0

As mention in the README.md also... Another way to make fetch@3 happen is to import node-fetch using the async import() supported in node v12.20

const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));

this works from commonjs also (the next request won't re-import node-fetch cuz modules gets cached) This can make the Node process boot up faster and only lazy loads the node-fetch when it's needed

here is another way to preload it:

const fetchP = import('node-fetch').then(mod => mod.default)
const fetch = (...args) => fetchP.then(fn => fn(...args))

You don't necessary have to convert your hole project to ESM just b/c we did it. You can also stay with the v2 branch - we will keep updating v2 with bug/security issues. But not so much with new features...

( Still recommend others to switch to ESM doe )

For TypeScript users who are only after the Types, you can do: import type { Request } from 'node-fetch' (this will not import or transpile anything - this typing annotation will just be discarded)

There is a hole section of how to import/require node fetch in cjs projects at #1279

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda