Blogs

Blogs

Sharing JS resources Across Modules

Your Liferay workspace is full of modules. Each module is starting to make use of the same JS resources and functions. Wouldn't it be nice if you could refactor your JS into a separate module that you can import elsewhere without publishing it to NPM? Well, here is one solution you can try! Please note I'll be referring to the code in this repo throughout the blog post .

1) Create your module you intend to share. For this I made use of the Liferay MVC Portlet Blade template, then added a package.json, and removed the java from the portlet. From here you can add all the JS you want, in the example I have I created a simple file that exports two functions that we will reference in another module.

2) In your bnd.bnd add a Provide-Capability and -includeresource. These will ensure that the the package.json is included in the build folder and the Provide-Capability is required for OSGi.

3) Create another module and in the build.gradle make use of the jsCompile task (https://dev.liferay.com/en/develop/reference/-/knowledge_base/7-1/js-transpiler-gradle-plugin#js-transpiler-base-plugin) which allows us to copy resources from a given path into the node_modules folder of our module (through the use of the npmInstall task and transpileJS task).

Here is the bnd.bnd:

4) In the JS for your second module you can import the JS from your first module and start to use it!

In our JS we are calling a reducer function to add or multiply values in array. This was done quickly, and could further be optimized. This example was created to show that I am able to call functions that I've created in a separate module here. For reference, here are the add and multiply functions being used:

Feel free to ask any additional questions below, this is more of a high level overview of how to accomplish something like this. The benefit is that I can place JS util functions, constants, or anything I want to share into a module that I can import elsewhere! See a gif below of the result and feel free to use the module's in the repo linked to get started.

 

anyway that its workable for normal native js rather than modern js?