Use third-party library development in LWC
Article Directory
In LWC, we can of course use third-party library code. Today I will
highCharts
be taught how you call.
Ready to work
-
Download the third-party library code you want to use locally.
-
As a static resource, upload to Salesforce.
-
In the
js
file:-
Import static resources
import resourceName from '@salesforce/resourceUrl/resourceName';
-
LightningElemengt
Import standard methods from modules:import { loadStyle, loadScript } from 'lightning/platformResourceLoader';
-
Explanation of standard methods
lightning/platformResourceLoader
Two methods are provided in the method: loadScript
and loadStyle
. Both methods return a Promises object, and the two can be chained or used in parallel.
loadScript(self, fileUrl): Promise
This method accesses a static JavaScript file resource, and a return load after the completion resolves
of Promise
self
Inherited theLightningElement
mapping component, the value must be in the methodthis
.LightningElement
This method can only be called in inherited modulesfileUrl
A string pointing to the path of the JavaScript file. To build this string, you need to declare a path to the static resource fileresourceName
The method of loading CSS files is similar:
loadScript(self, fileUrl): Promise
DOM manipulation in JavaScript
Although manual DOM manipulation in LWC components is not recommended, many third-party libraries will control the DOM.
So the added lwc:dom="manua"
attribute element will be redirected to an empty native HTML element, so its operation will be departing from the framework of LWC limit.
<template>
<div lwc:dom="manual"></div>
</template
Example
This component takes advantage of highCharts
the library shows the output of our group time each day:
First download the highcharts source code package/core JavaScript file and upload it as a static resource.
In VSCode, create a new component. Element of a package highcharts div
element, HTML code components as follows:
<template>
<div>
<div id="container" lwc:dom="manual"></div>
</div>
</template>
In JavaScript class file import loadStyle(可选)``````loadScript
method to import highcharts core document, which highcharts
is set when uploaded to a static resource resource name.
In the renderedCallback()
method, the first time render, we call the load method to load the style and method, since the method call will return Promise objects, so that we can use Promise.all()
to ensure that all files have been loaded successfully. In the callback function, when there is no error and the file is loaded, the working method of the third-party library will be called. 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 春季'
},
xAxis: {
allowDecimals: false,
type: 'datetime',
dateTimeLabelFormats: {
day: '%b %e'
},
title: {
text: '日期'
}
},
yAxis: {
startOnTick: true,
endOnTick: false,
maxPadding: 0.35,
title: {
text: '时间'
},
labels: {
format: '{value} mins'
}
},
tooltip: {
pointFormat: '{series.name} 学习了 <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:
-
To avoid naming conflicts, variable names the file path of static resources and third-party libraries in the method name can not be the same.
For example, it
HIGHCHARTS
is the path name of a static file andHighcharts
the method name of a third-party library. -
You must ensure that all files have been called before you can enter the working functions of the third-party library.
supplement
Since only one core JavaScript file is loaded in my code, here is how to load files in the file library, CSS files and multiple core files:
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 */ });