'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?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source