[Salesforce / LWC] Use third-party library development in LWC Use Third-Party JavaScript Libraries In LWC

Using third-party library development in LWC

Article directory

  • Use third-party library development in LWC
    • Preparation
    • Standard method explanation
    • DOM manipulation in JavaScript
    • example
      • A few things to note in the above code:
      • Replenish

In LWC, we can of course use code from third-party libraries. today i will use
highCharts will teach you how to call it.

Preparation

  1. Download the third-party library code you want to use locally.

  2. As a static resource, upload it to Salesforce.

  3. In the js file:

    • Import static resources

      import resourceName from '@salesforce/resourceUrl/resourceName';
      
    • Import the standard method from the LightningElemengt module:

      import {<!-- --> loadStyle, loadScript } from 'lightning/platformResourceLoader';
      

Explanation of standard methods

The lightning/platformResourceLoader method provides two methods: loadScript and loadStyle. Both methods return a Promises object, both can be chained or used in parallel.

loadScript(self, fileUrl): Promise

This method will access the JavaScript file in the static resource and return a Promise of resolves after loading

  • self inherits the mapping of the LightningElement component, and the value in the method must be this. This method can only be called in modules that inherit LightningElement
  • fileUrlA string pointing to the JavaScript file path. Building this string requires declaring a resourceName that points to a path to a static resource file

The method for loading CSS files is also similar:

loadScript(self, fileUrl): Promise

DOM manipulation in JavaScript

Although manual DOM manipulation in LWC components is not recommended, many third-party libraries will handle the DOM.

So the element with the added lwc:dom="manua" attribute will be redirected to an empty native HTML element, so that the operation on it will be out of the limitation of the LWC framework.

<template>
    <div lwc:dom="manual"></div>
</template

Example

This component utilizes the highCharts library to show our team’s daily output time:

First download the highcharts source package/core JavaScript file and upload it as a static resource.

In VSCode, create a new component. The element wrapping highcharts is a div element, so the HTML code of the component is as follows:

<template>
    <div>
        <div id="container" lwc:dom="manual"></div>
    </div>
</template>

In the JavaScript class file, import the loadStyle (optional) ``````loadScript method, and import the highcharts core file, where highcharts is set when uploading to static resources The specified resource name.

In the renderedCallback() method, when rendering for the first time, we call the loading method to load styles and methods. Since the calling method will return a Promise object, we can use Promise.all() to make sure all files loaded successfully. In the callback function, the working method of the third-party library will only be called when there are no errors and the files are loaded. In this way, we ensure that all methods and styles from the third-party library are correctly referenced to the environment and was used.

Below is my javascript code:

import {<!-- --> LightningElement } from "lwc";
import {<!-- --> loadScript } from "lightning/platformResourceLoader";
import HIGHCHARTS from "@salesforce/resourceUrl/highcharts";

export default class CDP_trial extends LightningElement {<!-- -->
  renderedCallback() {<!-- -->
    Promise. all([
      loadScript(this, HIGHCHARTS)
        .then(() => console.log("Highcharts loaded"))
        .catch(error => console.log("Error in loading Highcharts"))
    ])
    .then(() => {<!-- -->
        this. runHighcharts();
    })
    .catch(error => {<!-- -->
        window.console.log("The error is: " + error);
    });
  }
    
  runHighcharts() {<!-- -->
  Highcharts.chart(this.template.querySelector('div'), {<!-- -->
        chart: {<!-- -->
                type: 'area',
                zoomType: 'x',
                panning: true,
                panKey: 'shift'
            },
            title: {<!-- -->
                text: '2021 Spring'
            },
            xAxis: {<!-- -->
                allowDecimals: false,
                type: 'datetime',
                dateTimeLabelFormats: {<!-- -->
                    day: '%b %e'
                },
                title: {<!-- -->
                    text: 'Date'
                }
            },
            yAxis: {<!-- -->
                startOnTick: true,
                endOnTick: false,
                maxPadding: 0.35,
                title: {<!-- -->
                    text: 'time'
                },
                labels: {<!-- -->
                    format: '{value} mins'
                }
            },
            tooltip: {<!-- -->
                pointFormat: '{series.name} learned <b>{point.y}</b>mins'
            },
            legend: {<!-- -->
                enabled: true
            },

            series: [{<!-- -->
                name: 'FO',
                lineColor: Highcharts.getOptions().colors[1],
                color: Highcharts.getOptions().colors[2],
                fillOpacity: 0.3,
                data: [
                    163,90,60,148,0
                ],
                pointStart: Date.UTC(2021, 1, 22),
                pointInterval: 24 * 3600 * 1000 // one day
            }, {<!-- -->
                name: 'BZ',
                lineColor: Highcharts.getOptions().colors[2],
                color: Highcharts.getOptions().colors[3],
                fillOpacity: 0.3,
                data: [
                    120,141,67,141,0
                ],
                pointStart: Date.UTC(2021, 1, 22),
                pointInterval: 24 * 3600 * 1000 // one day
            }, {<!-- -->
                name: 'SZ',
                lineColor: Highcharts.getOptions().colors[3],
                color: Highcharts.getOptions().colors[4],
                fillOpacity: 0.3,
                data: [
                    90,0,0,0,0
                ],
                pointStart: Date.UTC(2021, 1, 22),
                pointInterval: 24 * 3600 * 1000 // one day
            }]
    });
  }
  
    
}

Points to note in the above code:

  • In order to avoid naming conflicts, the variable name of the file path of the static resource and the method name in the third-party library cannot be the same.

    For example, HIGHCHARTS is the path name of the static file, and Highcharts is the method name of the third-party library.

  • It is necessary to ensure that all files have been called before entering the work function of the third-party library.

Supplement

Since only one core JavaScript file is loaded in my code, here’s how to load the files in the library, CSS files and multiple core files for your reference:

import HIGHCHARTS from "@salesforce/resourceUrl/highchartsZip"
//...
Promise. all([
    loadScript(this, HIGHCHARTS + '/core/highcharts.source.js'),
    loadScript(this, HIGHCHARTS + '/core/3d.source.js'),
    loadScript(this, HIGHCHARTS + '/core/map.source.js'),
    loadStyle(this, HIGHCHARTS + '/style.css')
]).then(() => {<!-- --> /* callback */ });