![How to Share JavaScript Code in LWC](https://gokulrajan.com/wp-content/uploads/2023/11/Feature-Image.png)
How to Share JavaScript Code in LWC
To Share JavaScript Code between LWC components, create a new LWC service component and export the variables or functions that you want to share using standard JavaScript syntax.
mainCmp will be a standard LWC component.
sharedCmp will Service Component.
lwc
├──sharedCmp
├──sharedCmp.js
└──sharedCmp.js-meta.xml
└───mainCmp
├──mainCmp.html
├──mainCmp.js
└──mainCmp.js-meta.xml
JavaScriptwe have one more pattern for sharing the code in LWC: using additional js files
lwc
└───mainCmp
├──mainCmp.html
├──mainCmp.js
├──helper.js
└──mainCmp.js-meta.xml
JavaScriptIn this blog, we will be looking into the service component pattern.
Append the variable or function with an export keyword to export them, instead of exporting all of them at the end of the file.
export let PI = '3.14';
//or
export {PI}; // at the end of file after all declerations
JavaScriptDeclare and Export an arrow function: (Can’t be used to pass this context )
export const multiply=(a,b)=>{
return a*b;
}
JavaScriptDeclare and export named function ( we can pass LWC this context ):
export function Sum(a,b){
return a+b;
}
JavaScriptEntire sharedCmp [Service Component] code.
export function sum(a,b){
return a+b;
}
export function firstMessage(){
return `hello ${this.name} !!!!`;
}
export const multiply=(a,b)=>{
return a*b;
}
export let PI = '3.14';
sharedCmp.jswe can import all the exported variables and functions by using a wildcard (*).
import * as helper from 'c/sharedCmp';
JavaScriptReference an exported variable like this:
helper.PI;
JavaScriptCall a Function like this:
helper.sum(5,6);
JavaScriptIn order to pass this context to the helper method we can use call() :
helper.firstMessage.call(this);
JavaScriptEntire code for mainCmp.js
import { LightningElement } from 'lwc';
import * as helper from 'c/sharedCmp';
export default class MainCmp extends LightningElement {
name;
constructor(){
super();
this.name='rajan';
}
connectedCallback(){
this.test = '(First msg only)';
console.log('sum is ',helper.sum(5,6));
console.log('PI is ',helper.PI);
console.log('multiply is ',helper.multiply(3,4));
console.log('message using call ', helper.firstMessage.call(this));
}
}
mainCmp.jsLink for Reference : Share JavaScript Code | Lightning Web Components Developer Guide | Salesforce Developers
For More Content Related to LWC : lwc – Gokul Rajan