How To Fix Must Use Import To Load Es Module Discord.js
Solution 1:
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
constfetch = (...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)
constfetch = (...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
Solution 2:
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:
- Try removing this line from package.json to use only requires in your code.
- or keep this line and use import statements instead of require statements everywhere in your app (ES6).
- 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';
importDiscordfrom'discord.js';
EDIT: you can also remove node fetch or revert to branch v2 to keep using require.
Post a Comment for "How To Fix Must Use Import To Load Es Module Discord.js"