How to include third party libraries / modules in SAPUI5
- Contains functions that makes it easier to work with arrays
- A library with additional date and time functionalities
In this blog I’ll explain how you can use these libraries in your SAPUI5 app. I’ll use the library MomentJs to show you how.
First go to the website of Moment.js: https://momentjs.com/
Click on: “moment-with-locales.min.js”
Copy the content of the page.
In your UI5 project create a folder “libs”. This is the place to put in all the third party libraries.
In the folder “libs” we create a file “moment.js”
In this file we paste the code that we’ve copied from the MomentJS website.
The project structure will look like this.
One of the ways to include this library into your project could be including the library in the index.html page. Please, don’t do this, this will not work when your UI5 app is used in the Fiori Launchpad. The Fiori Launchpad will start your app from the Component.js and not from the Index.html .
The value in the define function will be undefined and should be different from the global name of the library. Therefore we used the name “momentjs”. The global name of the library is “moment” in this case so we cannot use that.
You can read more details about this in the API Refrence
|Third Party Modules
Although third party modules don’t use UI5 APIs, they still can be listed as dependencies in a sap.ui.define call. They will be requested and executed like UI5 modules, but their module value will be undefined.If the currently defined module needs to access the module value of such a third party module, it can access the value via its global name (if the module supports such a usage).Note that UI5 temporarily deactivates an existing AMD loader while it executes third party modules known to support AMD. This sounds contradictarily at a first glance as UI5 wants to support AMD, but for now it is necessary to fully support UI5 apps that rely on global names for such modules.
After that we can use moment in our controller by using the global name of the library. In this example I use moment to add 18 days to today and get the name of that day in English, French and Dutch.
As you can see, the SAPWebIDE still gives errors when using the library although we’ve included correctly! To fix this errors we have to add the following line at the top of the controller:
/* global moment:true */
Where “moment” is the name of the global library. For lodash it would look like this:
/* global _:true */
“_” is the global name for the lodash library.
This will fix the errors!
In the view we just bind some text fields to the JSONModel
And this will give the following result.
A basic example to show you how to include libraries in your SAPUI5 project in the SAPWebIDE without having errors!