Search code examples
ecmascript-6transpilernode-fetch

Transpiling node-fetch require returns error


I'm running into an issue with the node-fetch library. The new version (3.0.3) has "type": "module" in its package.json. This is a problem because I transpile my code from ES6 to regular js which uses require and then I get ...firebase_datasource.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. I can use an earlier version of node-fetch that doesn't contain "type": "module" in its package.json in its package.json, but that's not a solution. What's the correct way to handle this?


Solution

  • node-fetch's README explains what to do:

    CommonJS

    node-fetch from v3 is an ESM-only module - you are not able to import it with require().

    If you cannot switch to ESM, please use v2 which remains compatible with CommonJS. Critical bug fixes will continue to be published for v2.

    npm install node-fetch@2
    

    Alternatively, you can use the async import() function from CommonJS to load node-fetch asynchronously:

    // mod.cjs
    const fetch = (...args) => import('node-fetch').then(({default: fetch}) => fetch(...args));