Npm module with different code with and without proxy support

Viewed 22

How can I create a javascript library (distributed as module on npm) with different implementations depending on whether the environment it gets run in (transpiled to??) has proxy support or not?

As I understand it babel doesn't (at least easily) support transpilling proxies so this isn't easily fixable just via transpilation.

1 Answers

You have a few options:

1: Use a Proxy polyfill

An example is this (which I think should be good enough) or this.

2: Check whether the Proxy variable exists

Unless you declared a variable named Proxy, I think this should be good enough.

console.log(typeof Proxy !== 'undefined')

This will output a Boolean value whether Proxy is available.
Example usage of the above:

if(typeof Proxy !== 'undefined') {
  // run code that uses Proxies
  console.log('I can use Proxies here!')
}
else {
  // run code that doesn't use Proxies
  console.log('Oops! I can\'t use Proxies here!')
}

NOTE: You have to use typeof to check whether the Proxy variable exists or not, as it will just return undefined instead of throwing an error.

Related