Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

371
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda