Tuesday, March 19, 2019

How to import third party libraries in Lightning Web Components(lwc)

This post explains how to import third-party libraries in lightning web components(lwc).

We can not directly import the third party scripts in Lightning web components because Security purpose Salesforce restrict the importing scripts from third-party content delivery sites like cdnjs, jsdelivr, etc

1.  First, you need to download the scripts from third-party sites.
2.  Then upload the scripts in static resources.

check below link how to import static resources in Lightning web components
https://www.salesforcecodecrack.com/2019/01/how-to-access-static-resources-in.html

Import methods from platformResourceLoader module.
Syntax
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';

platformResourceLoader have two methods loadStyle, and loadScript. For both methods return type is Promise.

To know more about Javascript promises to check below link.
Javascript Promise

loadScript(self, fileUrl): Promise
self—A reference to the component. The value must be this.
fileUrl—A string that contains the path to the JavaScript file. To build the string, concatenate the resourceName and the path to the file within the static resource archive.

loadStyle(self, fileUrl): Promise
self—A reference to the component. The value must be this.
fileUrl—A string that contains the path to the CSS file. To build the string, concatenate the resourceName and the path to the file within the static resource archive.

Note:
Promise.all() method combine all promises into a single promise.
To invoke the platformResourceLoader methods we use renderedCallback() or connectedCallback() Methods based on the Requirement.

Examples:
if you are importing single script or CSS Files use below code
For script
loadScript(this, resourceName + '/lib.js')
    .then(() => { /* callback */ });

for CSS Files
loadStyle(this, resourceName + '/lib.css')
    .then(() => { /* callback */ });

If you are importing multiple scripts use below code.
Promise.all([
    loadScript(this, resourceName + '/lib1.js'),
    loadScript(this, resourceName + '/lib2.js'),
    loadScript(this, resourceName + '/lib3.js')
]).then(() => { /* callback */ });


Demo

In this Demo, I am importing two different third-party scripts, Jquery script, and CSS File.
thirdPartyLibraryDemo.html
<template>
    <lightning-card title="Third Party Library Demo" icon-name="custom:custom19">
        <p><b style="color:blue;">{successMessage}</b></p>
    </lightning-card>
</template>

thirdPartyLibraryDemo.js
import { LightningElement, track } from 'lwc';
// importing leaflet library from static resource
import leafletResource from '@salesforce/resourceUrl/leaflet';
// importing chartJS Library from static resource
import chartJSResource from '@salesforce/resourceUrl/chartJS';
// importing jquery library  from static resource
import jqueryResource from '@salesforce/resourceUrl/Jquery331';
// importing resource loader
import { loadScript, loadStyle } from 'lightning/platformResourceLoader';
// imported for to show toast messages
import { ShowToastEvent } from 'lightning/platformShowToastEvent';

export default class ThirdPartyLibraryDemo extends LightningElement {
    @track error;
    @track successMessage = '';

    renderedCallback() { // invoke the method when component rendered or loaded
        Promise.all([
            loadStyle(this, leafletResource +'/leaflet.css'), // CSS File
            loadScript(this, leafletResource + '/leaflet.js'),  // leaflet js file
            loadScript(this, chartJSResource + '/Chart.min.js'), // chart js file
            loadScript(this, jqueryResource), // jquery script
        ])
        .then(() => { 
            this.error = undefined;
            // Call back function if scripts loaded successfully
            this.showSuccessMessage();
        })
        .catch(error => {
            this.error = error;
            this.dispatchEvent(
                new ShowToastEvent({
                    title: 'Error!!',
                    message: error.message,
                    variant: 'error',
                }),
            );
        });
       
    }
    showSuccessMessage() { // call back method 
       this.successMessage = 'Scripts are loaded successfully!!';
       alert('Scripts are loaded successfully!!!');
    }
}

thirdPartyLibraryDemo.js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata" fqn="thirdPartyLibraryDemo">
    <apiVersion>45.0</apiVersion>
    <isExposed>true</isExposed>
    <targets>
        <target>lightning__AppPage</target>
        <target>lightning__RecordPage</target>
        <target>lightning__HomePage</target>
    </targets>
</LightningComponentBundle>

Result

4 comments:

  1. I keep getting an undefined error, it cannot load my script...

    ReplyDelete
    Replies
    1. did you solve it ?

      Delete
    2. I had this problem too - basically its because the library has already been loaded. I found the details here: https://www.desynit.com/dev-zone/lightning-web-components-and-shared-third-party-javascript-libraries

      Delete
  2. I am looking to change the background color of the lightning-card entire section. I am confused here in this example on how I can define that in the CSS File. Could you please update on how to change the background color with this method?

    ReplyDelete