Title: Having trouble with import from node-fetch? Let's figure it out
Hey folks,
So I’ve been trying to use import from node-fetch in my project, but it’s just not playing nice.
Sometimes it throws this weird error like *"Cannot use import statement outside a module"* or just straight-up refuses to work.
Anyone else run into this?
I’ve tried:
- Adding `"type": "module"` to package.json
- Using require() instead, but that feels outdated
- Reinstalling node-fetch, just in case
Still no luck. Am I missing something obvious?
Would love to hear how you guys got import from node-fetch working smoothly.
Thanks in advance!
ugh, node-fetch can be such a pain sometimes.
Try adding `--experimental-modules` flag when running your script if you're on an older Node version.
Also, make sure your file extension is `.mjs` if you're using modules. Or just stick with `.js` and keep `"type": "module"` in package.json.
Yo! Ran into this exact issue. Here’s what worked for me:
1. Delete `node_modules` and `package-lock.json`
2. Reinstall everything (`npm install`)
3. Use `import fetch from 'node-fetch';`
Sometimes the cache just gets weird. Also, check if you’re mixing require() and import—that can cause chaos.
If you’re getting the "Cannot use import statement outside a module" error, it’s likely a Node.js config issue.
Try this:
- Rename your file to `.mjs`
- Or add `"type": "module"` to package.json (which you already did)
Also, ensure you’re not using an ancient version of node-fetch. v3+ works better with ES modules.
Hey! Just a quick tip—if you’re using TypeScript, make sure your `tsconfig.json` has `"module": "ESNext"`.
Otherwise, the import from node-fetch might get compiled weirdly.
Also, `npm ls node-fetch` to confirm you’re not accidentally pulling in multiple versions.
Thanks everyone for the suggestions!
Tried a bunch of these—updating Node and sticking to `.mjs` files worked like a charm.
Still weird that it’s so finicky, but hey, it’s running now.
Quick Q: Anyone know why node-fetch doesn’t just work out of the box with ES modules? Seems like a common headache.
lol node-fetch is such a drama queen.
Try this hack:
`const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));`
Works as a temp fix if nothing else does. Not ideal, but gets the job done.
Check your file extensions! If you’re using `.js` with `"type": "module"`, it should work.
But if you’re mixing `.js` and `.mjs`, Node gets confused. Stick to one.
Also, `node --version` to confirm you’re on Node 14+. Older versions are a nightmare with import from node-fetch.