Export Functions And Variables From A Lightning Web Component


When you create a Lightning Web Component, it comes with some default code.

Our Lightning Web Component extends ‘LightningElement,’ allowing us to leverage various functions and variables seamlessly without additional configuration.

However, what if I desire a more streamlined Lightning Web Component with only specific variables and functions? Suppose I intend to use this LWC solely to house these elements, making them accessible to multiple other Lightning Web Components.

In such cases, we can employ a basic JavaScript class, encapsulate the desired functions and variables within it, and ultimately export it to any other component that requires them.

Here is an example code snippet:

function calculateTax(){

}

function calculatePrincipleInterest(){

}

const myRecordId = ‘xxxxxx’;

export default { calculateTax, calculatePrincipleInterest, myRecordId }
import { LightningElement } from 'lwc'
import { calculateTax, calculatePrincipleInterest, myRecordId } from ‘./helperScripts/helperScripts’

export default class ExploreHelper extends LightningElement{
   constructor(){
      super();
      calculateTax();
   }
}

I trust this proves beneficial!