Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

361
Views
Conditional import with ES Module ( fetch / node-fetch )

I'm writting a JS code that can be use eather for Node application or for JavaScript web browser application.

Since Node 17.5 it's now possible to use the native fetch API from JavaScript.

I wonder if there is a way to use a kind of conditinal import for ES Module working like this :

if fetch exist => use fetch
else import fetch from node-fetch

I've tried something like this :

if(!fetch) {
    import fetch from 'node-fetch'
}

...
fetch(url).then(res => ...)
...

But it raises an error as fetch is undefined. Note: I made my test using node@18

Has someone an idea to solve my probleme ?

Answer :

I Found a solution thanks to @Positivity's answer :

let fetcher = fetch ?? await import('node-fetch');

Then I use fetcher as fetch.
If I rename the variable to fetch it throw an error :

Cannot access 'fetch' before initialization

Finnaly found a solution to this error :

if(!fetch) {
    const fetch = await import('node-fetch');
}
// else => fetch is already declared
about 4 years ago · Santiago Trujillo
1 answers
Answer question

0

The import() call, commonly called dynamic import, is a function-like expression that allows loading an ECMAScript module asynchronously and dynamically into a potentially non-module environment.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import

so this should do a conditional import on supported node versions:

let fetch = fetch ?? await import('node-fetch')
about 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!