Hi Developers, Welcome again and in this tutorial we will see how we can share the code between Lightning Web Components.

To share code between components, create an ES6 module and export the variables or functions that you want to share.

An ES6 module is a JavaScript file that explicitly exports variables or functions that other modules can use. Modules make it easier to structure your code without polluting the global scope.

There are two ways to export functionality from an ES6 module.

A module can export a single default function or variable.

// utilJs.js
export default shpwToast (variant='info', mode='dismissable', title, message) { 
   const event = new ShowToastEvent({
        title: title,
        message: message,
        mode : mode,
        variant : variant
    });
    return event;
}

To import the method from the utility js file use the syntax like below

// consumerComponent.js
import { shpwToast } from 'c/utilJs';

Refer below video to see the complete code in action

If you have any queries or any other questions you can reach me out @cloudyamit or email me sfdcpanther@gmail.com #SFDCPanther


Reference & Sources

Leave a Reply

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