Use Polyfills to use JavaScript ES6 features with Phantom.js
I encountered some errors recently writing JavaScript tests in Phantom.js: ReferenceError: Can't find variable: Promise
. This seemed like a strange error and ultimately it turns out that phantom.js
is significantly lagging behind overall browser support of JavaScript ES6 features, like Promises. As of this writing, all modern browsers support Promises, however Phantom won't support any ES6 features for quite some time. There are lots of other features not supported by Phantom.js, like Intl.js
, the ECMAScript (ECMA-402) Internationalization API.
That said, there are some easy workarounds to continue using ES6 features with Phantom.js, or in another context where said feature is unavailable. First, you can use a popular complier like Babel.js, to transform your ES6 JavaScript into a backwards-compatible version. Or you can use simple polyfills like promise-polyfill
.
A polyfill is a browser fallback, made in JavaScript, that allows functionality you expect to work in modern browsers to work in older browsers, e.g., to support new features in older browsers.
Polyfills make sense if you're going to be using a limited sub-set of ES6 features and are okay adding a dependencies. If you plan on using the ES6 whole kit and caboodle, you're better off setting up Babel.js
.
All you need to do is install the package and you can go about using Promises in whatever context you like.
npm install promise-polyfill
Not every polyfill will be this simple and it goes without saying that you should read the docs before installing any polyfills.
- [1]Can I Use
- [2]StackOverflow
- [3]NPM