Friday, May 1, 2020

Sharing javascript code between lightning web component

In this blog we are going to see how can we share javascript code to other javascript file of same component bundle or different component bundle.

When we create lightning web component, it get created with component bundle which contains below file:

                               


We can't write our entire logic in myComponent.js file. Code reusability is main factor while developing any application. So there can be two possibilities to maintain our reusable javascript code and share that code with other javascript file :

  1. We can create one more  Js file(ES6 module)  in same component bundle. Use standard export statement to export any function or variable. myComponent.js file can use standard import statement to use exported function or variable. See below reuse.js and myComponent.js file.

reuse.js file:

Create Addition function in reuse.js file and use export keyword to export Addition function.



  
myComponent.js:

use import statement in myComponent.js to import Addition function from reuse.js file.





2. The other way to maintain reusable code is to Create another component bundle called util and import util bundle to myComponent.js file.

     
util.js file:

In util.js file we have created subtraction and multiplication method and exported using export keyword.





Lets see how you can import this component module to  myComponent.js file .

myComponent.js:

while importing a util component module to myComponent.js we have to mention the "namespace/moduleName" . In our case it will be "c/util" where "c" is default namespace to salesforce and "util" is name of our component bundle.