Today, I will explain to you how to import third-party libraries in LWC (Lightning Web Component). Third-party scripts cannot be directly imported into Lightning web components due to Salesforce’s security policy. In my example, I will use numeral.js for input number validation. Numeral.js allows you to use a long list of built-in formatting and locales. It also allows customization of your formatting and adds additional ones that might not be in the library (more on that later).
Steps to import Third-Party Library:-
Step 1: Create or Download the Zip file link.
Step 2: Upload this zip file to a static resource.
Go to Setup > Static Resources > New
Import the library by its static resource name.
import resourceName
from'@salesforce/resourceUrl/resourceName';
For example, if you named the static resource PackageResources:
import PackageResources
from '@salesforce/resourceUrl/PackageResources;
Imports methods from platformResourceLoader module
import {loadScript} from'lightning/platformResourceLoader';
Load the library and call its function in a then() method
Step 3: Now we will see how to achieve this through coding.
Promise in JavaScript lets asynchronous methods return values like synchronous methods, instead of immediately returning the final value. A Promise is always in one of the below three states:
a. Pending: This is the initial state. It is neither fulfilled nor rejected.
b. Fulfilled: The Promise is completed successfully.
c. Rejected: The Promise is failed or there is an error.
A promise is said to be settled if it is fulfilled or rejected, but not pending.
The then() method in JavaScript has been defined in the Promise API and is used to deal with asynchronous tasks such as an API call.
import { LightningElement } from 'lwc';
import {loadScript} from 'lightning/platformResourceLoader';
import locale from '@salesforce/i18n/locale';
import PackageResources from '@salesforce/resourceUrl/PackageResources';
import {ShowToastEvent} from 'lightning/platformShowToastEvent';
export default class Test extends LightningElement {
renderedCallback() {
if (!this.scriptLoaded) {
this.loadScript();
}
}
loadScript() {
Promise.all([
loadScript(this, PackageResources +
'/numeral/numeral206.js'),
loadScript(this, PackageResources +
'/numeral/locales.js')
])
.then((response) => {
// here you can call functions.
this.initNumeralHelpers();
this.scriptLoaded = true;
})
.catch(error => {
const event = new ShowToastEvent({
title: 'error',
message:'LoadScrip is not loaded.'+ error,
});
this.dispatchEvent(event);
});
}
}
Happy!! To help you add to your knowledge. You can leave a comment to help me understand how the blog helped you. If you need further assistance, please leave a comment or contact us. You can click on "Reach us" on the website and share the issue with me.
Blog Credit:
A. Kumar
Salesforce Developer
Avenoir Technologies Pvt. Ltd.
Reach us: team@avenoir.ai
Comments