Share the JavaScript code between Lightning Web Component

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 [email protected] #SFDCPanther

Reference & Sources

 

 

Amit Singh
Amit Singh

Amit Singh aka @sfdcpanther/pantherschools, a Salesforce Technical Architect, Consultant with over 8+ years of experience in Salesforce technology. 21x Certified. Blogger, Speaker, and Instructor. DevSecOps Champion

Articles: 299

Newsletter Updates

Enter your email address below and subscribe to our newsletter

2 Comments

  1. How can we define the events method in util.js and pass event parameters, like onclick(event)?

    • 1. You have to create a method in your shared JS which will accept parameter and do perform the logic
      2. Export that method
      3. Import in your main JS Class
      4. Use that

      Here is the sample method which makes a server (apex) call using utility method and then again calls the success/error methods

      You have to try it from your side.


      const _servercall = (_serveraction, _params, _onsuccess, _onerror) => {
      if (!_params) {
      _params = {};
      }
      _serveraction(_params)
      .then(_result => {
      if (_result && _onsuccess) {
      _onsuccess(_result);
      }
      })
      .catch(_error => {
      if (_error && _onerror) {
      _onerror(_error);
      }
      });
      };

Leave a Reply

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

Discover more from Panther Schools

Subscribe now to keep reading and get access to the full archive.

Continue reading