Search code examples
javascriptpromisecordova-plugins

how do I include a Promise polyfill in a Cordova plugin


I'm testing a Cordova plugin (https://github.com/mutualmobile/cordova-bluetoothle/blob/master/src/www/bluetoothle.js) that uses the Javascript Promise API. The plugin will be used in an Android app which has a webview that runs using Chrome 30. This version of Chrome is relatively old and doesn't natively support the Promise API. Rather than use Crosswalk I want to include the Promise API as a polyfill using code from promisejs.org (https://www.promisejs.org/polyfills/promise-6.1.0.js). Can anyone advise on how I include the polyfill into the plugin linked to above? I've tried adding the following to plugin.xml file but can't seem to work out how to reference it in bluetoothle.js

<js-module src="www/promise-6.1.0.js" name="Promise">
    <clobbers target="promise"/>
</js-module>

Any help would be much appreciated.


Solution

  • The promisejs.org polyfill is packed in an unconventional way, you could use the taylorhakes/promise-polyfill that is using a simple module.exports at the end of the module.

    In order to preserve the native Promise just alter the export line from:

    module.exports = Promise;
    

    to:

    module.exports = root.Promise || Promise;
    

    and add this to your config.xml

    <js-module name="Promise" src="www/Promise.js">
        <clobbers target="Promise" />
    </js-module>