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

380
Visualizações
Making fetch() work in both browser and node

I have a small typescript plugin that runs in the browser, which uses fetch, e.g. fetch(url).

To test the plugin using mocha, mocha runs in a node environment and because of this, fetch isn't implemented.

It can be made to work in node using:

declare const require: any
fetch = require('cross-fetch');
fetch(url)

However, the require statement raises an ugly error when running in the browser.

Ideally I'd like to have something like:

if(typeof fetch !== 'undefined'){ const fetch = require('cross-fetch'); }
fetch(url)

However, this obviously scopes fetch to the if statement and it can't be used globally. If I try

if(typeof fetch !== 'undefined'){ fetch = require('cross-fetch'); }

Then typescript complains that fetch is already defined as a function (typescript is basing this on the browser environment). So it won't compile.

Is there a way to either 1.) tell typescript that fetch might NOT be defined even though it thinks that it is, or 2.) to enable fetch globally some other way


Meta-question: how are other people testing their browser-based javascript? Surely there's an easier way than making the javascript work in a node environment?

about 4 years ago · Juan Pablo Isaza
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