Search code examples
gruntjssapui5babeljsbabel-polyfillui5-tooling

What would be the best way to include babel polyfill in a sapui5 project?


We use grunt as a task runner and we use the same settings for grunt as openui5 developers recommend and use.

https://github.com/SAP/grunt-openui5

https://github.com/SAP/openui5/blob/master/docs/tools.md

We would like to add babel-polyfill to the project (so we could use the latest javascript features) when we build the application just like how you would do it with e.g.: webpack. Thanks for you answers in advance.


Solution

  • The options that you have are described in the official documentation of babel polyfill. I will describe a little when I think each of them should be used.

    It depends how you are actually using the application afterwards: is it a standalone UI5 app (i.e. you run it directly from a HTML file) or is it a Fiori app (i.e. you run it from the Fiori Launchpad)?

    If it is a standalone application, then the easiest and most non-intrusive way of including the babel-polyfill is to simply include the dist/polyfill.js in you HTML file through a <script> tag.

    If it is a Fiori app, then the only chance you have is to prepend the polyfill to one of your script files. It has to run before anything else, so I would prepend it to the Component-preload.js file that you obtain during the build phase. To do this "prepend" operation with grunt, you can use the grunt-contrib-concat plugin.

    Another possibility is to simply require the polyfill inside the Component module. You can do this in the sap.ui.define call in the Component file:

    // the oPolyfill parameter most likely will have nothing in it
    // as the polyfill most surely does not use the SAP AMD system
    sap.ui.define(["./path/to/polyfill"], function(oPolyfill) {
        //...
    }); 
    

    When using this strategy, the generated Component-preload.js file will contain also the polyfill and the polyfill would be loaded just before your Component code would start running.

    Keep in mind that, if you use any of these approaches in a Fiori Launchpad environment, the polyfill will affect other Fiori apps as well. This is unavoidable, as the polyfill modifies global variables as specified in the documentation of babel:

    The polyfill adds to the global scope as well as native prototypes like String in order to do this.