Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

362
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda