208

I'm trying to make a Discord bot that just says if someone is online on the game.

However I keep getting this message:

[ERR_REQUIRE_ESM]: require() of ES Module from not supported. Instead change the require of index.js in... to a dynamic import() which is available in all CommonJS modules.

This is my code:

    module.exports = {
        name: 'username',
        description: "this is the username command",
        async execute(message, args) {

            const fetch = require('node-fetch');

            if (args.length !== 1) {
                return message.channel.send("invalid username wtf")
            }

            const ign = args[0]

            if (ign.length > 16 || ign.length < 3) {
                return message.channel.send("invalid username wtf")
            }

            const uuid = await fetch(`https://api.mojang.com/users/profiles/minecraft/${ign}`).then(data => data.json()).then(data => data.id).catch(err => message.channel.send("error wtf"));
            const onlineInfo = await fetch(`https://api.hypixel.net/status?key=${john}&uuid=${uuid}`).then(data => data.json());

            if (uuid.length !== 32) {
                return;
            }

            if (onlineinfo.success) {
                if (onlineinfo.session.online) {
                    message.channel.send("they are online")
                }
                else {
                    message.channel.send("they are offline")
                }
            }
            else {
                message.channel.send("hypixel api bad wtf")
            }
        }
    }

This is my package.json file:

{
    "name": "discordbot",
    "version": "1.0.0",
    "main": "main.js",
    "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "start": "node main.js"
    },
    "author": "",
    "license": "ISC",
    "description": "",
    "dependencies": {
        "discord.js": "^13.0.1",
        "node-fetch": "^3.0.0"
    }
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
N-Man
  • 2,851
  • 2
  • 4
  • 7
  • I don't have all the module.exports stuff, do I need that? I just say export class whatever, is that wrong? – pabrams Nov 25 '21 at 01:25
  • But I thought `"type": "module",` should only be used IF you didn't rename your files as *.mjs*. – Sandburg Jul 15 '22 at 10:38
  • In my case it was about the way I'd compiled using `npx tsc app.ts` while this won't pick the configuration file (tsconfig.json), use just `npx tsc` instead. :) – aderchox Mar 15 '23 at 23:58

3 Answers3

81

The node-fetch latest version doesn't use the require() syntax to import the package. You need to go to your package.json and type

 { 
   "type": "module",
 }

to use the import syntax and import node-fetch, but then you can't use require for any other packages. You need to work with import statement only.

Or you can use other packages, such as Got or Axios, which can be imported by the require() syntax.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kabeer Arora
  • 961
  • 1
  • 4
  • 7
  • 8
    I use require() in a different file in my code, so how come it works there? – N-Man Sep 07 '21 at 18:55
  • 40
    I already do this, but I still get the error, because the typescript transpiler puts the requires back, in the .js. How do I get it to stop doing that? – pabrams Nov 25 '21 at 00:54
  • 15
    doesn't work, still throws Error [ERR_REQUIRE_ESM]: require() of ES Module not supported. Although i don't have a single require() in my code anymore. – FireFuro99 Dec 17 '21 at 01:49
  • once i add this to my package.json will i still be able to use require for other packages? – kd12345 Jan 09 '22 at 09:10
  • Can they work together? ES Module and CommonJS? I thought this was done by the extension (*.mjs* /vs/ *.js*) – Sandburg Jul 15 '22 at 10:40
  • 7
    Same, this doesn't work because the typescript transpiler adds requires. – dessalines Jul 29 '22 at 03:27
  • 2
    `got` v12 doesn't work with `require()`, you have to use `import`. "This package is native ESM and no longer provides a CommonJS export. If your project uses CommonJS, you'll have to convert to ESM or use the dynamic import() function." – Thomas David Kehoe Oct 05 '22 at 18:01
  • what do you mean by "type {type: module}", where exactly in the package.json should we do it? – serge Dec 15 '22 at 12:12
72

I figured it out. I just had to downgrade node-fetch to 2.6.6, as the higher versions only use ESM, which caused a lot of errors.

Duc Filan
  • 6,769
  • 3
  • 21
  • 26
N-Man
  • 2,851
  • 2
  • 4
  • 7
  • 3
    When I try that, I get compile time errors from typescript, like it can't import node-fetch, can't find node-fetch, can't find type definitions for node-fetch, blah blah blah... and then if I add the type definitions it says I don't need those... wtf is up with typescript and node all the time – pabrams Nov 25 '21 at 01:19
  • 1
    You then need to import like this `import * as fetch from 'node-fetch';` – Joe Keene May 04 '22 at 10:12
  • 2
    Still works. Still dumb. – Michael Jul 25 '22 at 14:24
  • 22
    This is so stupid. Why don't import an require just not work together nicely... – Quinten C Aug 18 '22 at 12:21
  • What is ESM? [ECMAScript module](https://hacks.mozilla.org/2018/03/es-modules-a-cartoon-deep-dive/)? – Peter Mortensen Aug 19 '22 at 11:38
  • may this link be useful https://bobbyhadz.com/blog/javascript-error-err-require-esm-of-es-module-node-fetch – r.a.shehni Nov 29 '22 at 12:39
  • Make sure you delete your node_modules folder and package-lock.json file after updating package.json. Then you should be able to run npm install and have it working – Real.Cryptc May 12 '23 at 15:48
37

node-fetch v3 recently stopped support for the require way of importing it in favor of ES Modules. You'll need to use ESM imports now, like:

import fetch from "node-fetch";

at the top of your file.

iamkneel
  • 1,303
  • 8
  • 12
  • 88
    I already do this, and it doesn't help. – pabrams Nov 25 '21 at 01:19
  • 2
    To be able to import it you need to follow the steps in this reply: https://stackoverflow.com/a/69089164/12152456 –  Dec 09 '21 at 19:37
  • A blessing of an answer. Scratching my head for 30 minutes before stumbling up on this answer that solved my problem. Thank you! – priyamtheone Sep 05 '22 at 17:48
  • 3
    Error: "Cannot use import statement outside a module" – WebDev-SysAdmin Nov 06 '22 at 21:42
  • 2
    @pabrams: this link help me https://bobbyhadz.com/blog/javascript-error-err-require-esm-of-es-module-node-fetch – r.a.shehni Nov 29 '22 at 12:41
  • 8
    It's absolutely absurd that all package dependencies need to use the same module import type as the running app. How the Node.js developers thought that breaking backward compatibility in an ecosystem where everything depends of everything would work well is beyond me. – Jacob Stamm Apr 18 '23 at 02:41