Salesforce Interview Questions & Answers Book is now available!

Grab Now

LWC

Export functions and variables from a Lightning Web Component

When you create a Lightning Web Component it’s going to have some boiler plate code. Our Lightning Web Component is going to extend ‘LightningElement’ that’s…

By Teja, ex-Salesforce engineer · Updated February 7, 2021 · 1 min read

When you create a Lightning Web Component it’s going to have some boiler plate code.

Our Lightning Web Component is going to extend ‘LightningElement’ that’s how we use a few functions and variables in our Lighting Web Components and they work off the hook without any configuration.

What if I don’t want all the features that we get access to off the bat in a typical Lightning Web Component and what if I want to use the LWC only to have some variables and functions, such that these helper functions and variables will be used my multiple other Lightning Web Components?

We can have a plain old JavaScript class, house a few functions and variables in it, then finally export it into any other component that needs them.

Here is a sample code

function calculateTax(){

}

function calculatePrincipleInterest(){

}

const myRecordId = ‘xxxxxx’;

export default { calculateTax, calculatePrincipleInterest, myRecordId }

helperScripts.js

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

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

exploreHelper.js

Hope this is helpful!

Learn it by building it

Every course, every code repository, the discussion group and certificates of completion — one subscription.

Keep me in the loop!

Email me when a new episode is published (promise, I will not spam you)

You're signing up to receive emails from Salesforce Casts