How to Share JavaScript Code in LWC

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
JavaScript

we 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
JavaScript

In 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
JavaScript

Declare and Export an arrow function: (Can’t be used to pass this context )

export const multiply=(a,b)=>{
    return a*b;
}
JavaScript

Declare and export named function ( we can pass LWC this context ):

export function Sum(a,b){
    return a+b;
}
JavaScript

Entire 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.js

we can import all the exported variables and functions by using a wildcard (*).

import * as helper from 'c/sharedCmp';
JavaScript

Reference an exported variable like this:

helper.PI;
JavaScript

Call a Function like this:

helper.sum(5,6);
JavaScript

In order to pass this context to the helper method we can use call() :

helper.firstMessage.call(this);
JavaScript

Entire 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.js

Link for Reference : Share JavaScript Code | Lightning Web Components Developer Guide | Salesforce Developers

For More Content Related to LWC : lwc – Gokul Rajan

Leave a Reply

Your email address will not be published. Required fields are marked *

Verified by MonsterInsights