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

378
Vistas
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 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