Skip to content

Loading node-fetch@3 in CJS and ESM #1279

Closed
@jimmywarting

Description

@jimmywarting

Pure ESM package

node-fetch is an ESM-only module - you are not able to import it with require(). You don't necessary have to convert your hole project to ESM just b/c we did it. There are ways to load ESM modules in cjs package too (more about this in FAQ). You can also stay with the v2 branch - We will keep updating v2 with bug/security issues. But not so much with new features...

This means you have the following choices:

  1. Use ESM yourself. (preferred)
    Use import fetch from 'node-fetch' instead of const fetch = require('node-fetch') to import the package. You also need to put "type": "module" in your package.json and more. Follow the below guide.
  2. you could use async import(…) from CommonJS instead of require(…). This is supported in CommonJS also
  3. Stay on the existing version of the package until you can move to ESM.

You also need to make sure you're on the latest minor version of Node.js. At minimum Node.js 12.20, 14.14, or 16.0.

I would strongly recommend moving to ESM. ESM can still import CommonJS packages, but CommonJS packages cannot import ESM packages synchronously.

ESM is natively supported by Node.js 12.17 and later.

FAQ


Have questions about another tools? look trough other issues or ask new ones
We will continue to update this with new solutions from other accepted answers

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions