You can use external JavaScript libraries in your portlets (i.e., anything but Metal.js, jQuery, or Lodash, which are included by default). There are a few methods you can use to make external libraries available. The method you should choose depends on the external libraries you plan to use and how you plan to use them.
This tutorial covers how to adapt external libraries for the JavaScript Loaders.
Configuring Libraries to Support UMD
If you’re the owner of the library, you should make sure that it supports UMD (Universal Module Definition). You can configure your code to support UMD with the template shown below:
// Assuming your "module" will be exported as "mylibrary"
(function (root, factory) {
if (typeof Liferay.Loader.define === 'function' && Liferay.Loader.define.amd) {
// AMD. Register as a "named" module.
Liferay.Loader.define('mylibrary', [], factory);
} else if (typeof module === 'object' && module.exports) {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
// Browser globals (root is window)
root.mylibrary = factory();
}
}(this, function () {
// Your library code goes here
return {};
}));
Next you can learn how to use libraries that you host.
Using Libraries That You Host
If you’re hosting the library (and not loading it from a CDN), you must hide the Liferay AMD Loader to use your Library. Follow these steps:
-
Open the Control Panel, navigate to Configuration → System Settings.
-
Click JavaScript Loader under Platform → Infrastructure.
-
Uncheck the
expose global
option.
Now you know how to adapt external libraries for Liferay’s JavaScript Loaders.