Once you’ve
exposed your modules,
you can use them in your portlet via the aui:script
tag’s require
attribute.
By default, Liferay DXP automatically composes an npm module’s JavaScript variable
based on its name. For example, the module my-package@1.0.0
translates to the
variable myPackage100
for the <aui:script>
tag’s require
attribute. This
means that each time a new version of the OSGi bundle’s npm package is released,
you must update your code’s variable to reflect the new version. You can use the
JSPackage
interface
to obtain the module’s package name and create an alias to reference it, so the
variable name always reflects the latest version number!
Follow these steps:
-
Retrieve a reference to the OSGi bundle’s npm package using the
getJSPackage()
method:JSPackage jsPackage = _npmResolver.getJSPackage();
-
Grab the npm package’s resolved ID (the current package version, in the format
<package name>@<version>
, defined in the OSGi module’spackage.json
) using thegetResolvedId()
method and alias it with theas myVariableName
pattern. The example below retrieves the npm module’s resolved ID, sets it to thebootstrapRequire
variable, and assigns the entire value to the attributebootstrapRequire
. This ensures that the package version is always up to date:renderRequest.setAttribute( "bootstrapRequire", jsPackage.getResolvedId() + " as bootstrapRequire");
-
Include the reference to the
NPMResolver
:@Reference private NPMResolver _npmResolver;
-
Resolve the
JSPackage
andNPMResolver
imports:import com.liferay.frontend.js.loader.modules.extender.npm.JSPackage; import com.liferay.frontend.js.loader.modules.extender.npm.NPMResolver;
-
In the portlet’s JSP, retrieve the aliased attribute (
bootstrapRequire
in the example):<% String bootstrapRequire = (String)renderRequest.getAttribute("bootstrapRequire"); %>
-
Finally, use the attribute as the
<aui:script>
require attribute’s value:<aui:script require="<%= bootstrapRequire %>"> bootstrapRequire.default(); </aui:script>
Below is the full example *Portlet
class:
public class MyPortlet extends MVCPortlet {
@Override
public void doView(
RenderRequest renderRequest, RenderResponse renderResponse)
throws IOException, PortletException {
JSPackage jsPackage = _npmResolver.getJSPackage();
renderRequest.setAttribute(
"bootstrapRequire",
jsPackage.getResolvedId() + " as bootstrapRequire");
super.doView(renderRequest, renderResponse);
}
@Reference
private NPMResolver _npmResolver;
}
And here is the corresponding example view.jsp
:
<%
String bootstrapRequire =
(String)renderRequest.getAttribute("bootstrapRequire");
%>
<aui:script require="<%= bootstrapRequire %>">
bootstrapRequire.default();
</aui:script>
Now you know how to reference an npm module’s package!
Related Topics
Obtaining an OSGi bundle’s Dependency npm Package Descriptors