Once you’ve
exposed your modules,
you can use them in your portlet via the aui:script
tag’s require
attribute.
You can load the npm module in your portlet using the
npmResolvedPackageName
variable, which is available by default since
Liferay DXP 7.2. You can then create an alias to reference it in your portlet.
Follow these steps:
-
Provide a
Web-ContextPath
in your bundle’sbnd.bnd
file:Web-ContextPath: /my-module-web
-
Make sure the
<liferay-frontend:defineObjects />
tag is included in your portlet’sinit.jsp
. This makes thenpmResolvedPackageName
variable available, setting it to your project module’s resolved name. For instance, if your module is calledmy-module
and is at version2.3.0
, the implicit variablenpmResolvedPackageName
is set tomy-module@2.3.0
. This lets you prefix any JS modulerequire
or soy component rendering with this variable. -
Use the
npmResolvedPackageName
variable along with the relative path to your JavaScript module file to create an alias in the<aui:script>
’srequire
attribute. An example configuration is shown below:<aui:script require='<%= npmResolvedPackageName + "/js/my-module.es as myModule" %>'> </aui:script>
-
Use the alias inside the
aui:script
to refer to your module:<aui:script require='<%= npmResolvedPackageName + "/js/my-module.es as myModule" %>'> myModule.default(); </aui:script>
Now you know how to use an npm module’s package!