Skip to content

[3.0.0-beta.10] Can't import node-fetch when using TypeScript in CJS mode #1226

@SomaticIT

Description

@SomaticIT

When upgrading node-fetch to v3.0.0-beta.10 in a TypeScript project which compile modules in CommonJS mode, the following error occured:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /tmp/node-fetch-test/node_modules/node-fetch/src/index.js
require() of ES modules is not supported.
require() of /tmp/node-fetch-test/node_modules/node-fetch/src/index.js from /tmp/node-fetch-test/index.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 /tmp/node-fetch-test/node_modules/node-fetch/src/index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /node-fetch-test/node_modules/node-fetch/package.json.

Reproduction

Steps to reproduce the behavior:

  1. Create an empty project:
npm init
npm i -D typescript
npm i [email protected]
npx tsc --init
  1. Create a file index.ts with the following code:
import fetch from "node-fetch";

(async () => {
    const res = await fetch("https://api.github.com/repos/touchifyapp/player/releases/latest", {
        headers: { Accept: "application/vnd.github.v3+json" }
    });

    console.log(await res.json());
})();
  1. Run the project:
tsc -p .
node index.js

Expected behavior

It should be able to import node-fetch correctly.

Many projects are using commonjs. When using TypeScript in cjs mode, it is not possible to mix require and import statements. Even in traditional javascript projects, importing an ES module is a mess. you have to use the async import() syntax, you can't import the module as usual.

I think we should provide both ESM and CJS versions of the package to ensure all users can migrate to node-fetch v3.
We can use package.json exports configuration to ensure projects are using the appropriate version of the module depending on their configuration.

The simplest and quickest method could be to use esbuild which can transpile esm modules to cjs.

Your Environment

software version
node-fetch 3.0.0-beta.10
node 14.15.3
npm 7.19.1
Operating System WSL 2
typescript 4.3.5

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions