Sometimes we need to share JavaScript code in Lightning Web Components (LWC). As code reusability is good feature and we can use same in LWC as well. To share JavaScript code between Lightning Web Components we need to create ES6 module. An ES6 module is a JavaScript file that explicitly exports variables or functions that other modules can use. Modules make it easier to structure our code without polluting the global scope.
Previously we can’t use the export
or import
statement in a JavaScript file to export or import variables, functions, classes or any other entity to/from other JS files. But now we can use them and we can include variable of one file into another file.

So today we will check how we can create reusable JavaScript code in Lightning Web Components.
Create Utility Lightning Web Components
We will create one LWC which will act as utility method. For this we only need JS and meta xml file. We will export our function from Utility file.
For demo purpose we will use regex to validate email address.
lwcUtility.js
export function emailValidator (email) {
const re = /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
lwcUtility.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>50.0</apiVersion>
<isExposed>false</isExposed>
</LightningComponentBundle>
You have notice that we have defined function using export keyword here. Now we need to create another component in which we will import this function.
Create Demo Component
Now we will create second component. So in that component we will import validator module and will use it.
<template>
<lightning-card title="Validate Email using ES6 Code">
<lightning-input class="input" type="text" label="Enter email"></lightning-input>
<div slot="actions">
<lightning-button label="Validate Email" onclick={validateEmail}></lightning-button>
</div>
</lightning-card>
</template>
import { LightningElement } from 'lwc';
import {emailValidator } from 'c/lwcUtility';
export default class Democode extends LightningElement {
validateEmail() {
//Get email address
let input = this.template.querySelector(".input").value;
let emailResult = emailValidator(input);
if(emailResult)
alert(input +" is valid Email.");
else
alert(input +" is not a valid Email.");
}
}
So here we are importing that validator method. We can pass parameters and get the response. A module can also export named functions or variables. The component that imports the function uses the exported names. We can can export all resources from another module with a relative file path.
Like my Instagram page for more updates.
So now we can easily Share JavaScript Code in Lightning Web Components. Do you like to add anything here, let me know in comments. Happy Programming 🙂
1 thought on “Share JavaScript Code in Lightning Web Components”