Using Third-Party JavaScript Libraries in Lightning Web Components

At times we might have to make use of a third party library and use it in LWC. There is no way we can use a CDN and include it in <script></script> tags in a Lightning Web Component.

So the route that we are gonna take it is using static resources in Lightning Web Component.

Create or download the library file and push it to static resources. From the static resources using the standard out of the box named imports to fetch a reference to Static Resource and use it in the controller.js file.

This is how the controller.js file is going to look like.

/*
 * ExploreStaticResourceInLWC
 */

import { LightningElement } from 'lwc';

//these are named exports to pull JS and CSS files from
//static resources.
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';

//interest is the name of the static resource we uploaded.
//Check this https://www.kkteja.com/nOu8pqXR

//am adding the static resource file also in this folder. 
import interest from '@salesforce/resourceUrl/interest';

export default class ExploreStaticResourceInLWC extends LightningElement {
    renderedCallback() {
        loadScript(this, interest).then(() => {
            //this is the name of the function that’s present
            //in the uploaded static resource.
            const interest = myLib.calculatePrincipleInterest(4567);
            console.log(interest);
        });
    }
}
ExploreStaticResourceInLWC.js file that is invoking a function in static resources

Create a JavaScript file like this and upload it to static resources. The name of the JS file is going to be calculatePrincipleInterest.js

/*
 * calculatePrincipleInterest.js
 */
window.myLib = (function() {
    return {
        calculatePrincipleInterest: function(a) {
            return a* 10.9;
        }
    };
}());
calculatePrincipleInterest.js

This is how the static resource is going to look like.

Using static resources in Lightning Web Component is going to be very handy as we can provide a very high level of abstraction and have only the necessary code in the Lightning Web Components.