How to use 3rd Party Libraries with Lightning Web Components

We’ve all been there.

Pining for a chance to use some of the cool JavaScript libraries like jQuery, MomentJS or Chart.js? Well now you can!

The LWC framework makes it easy to use external JavaScript libraries to expand functionality beyond what Salesforce can provide, take Two.js for example – Two.js is a 2d graphics library that allows the drawing and connecting of shapes, ideal for ERD projects or visualisation.

Enough chit chat, let’s see how it works!

The first step is to upload our JavaScript library as a Static Resource within Salesforce, lets do it:

  1. Click Setup
  2. Search ‘Static Resource’
  3. Click ‘New’, upload your JavaScript file and name it

Once the external JavaScript library has been uploaded as a Static Resource, we can move onto generating the LWC:

import { LightningElement, api, track } from ‘lwc’;
import { loadScript } from ‘lightning/platformResourceLoader’;
import TwoJs from ‘@salesforce/resourceUrl/TwoJs’;

export default class TwoJsWrapper extends LightningElement {
    @api width;
    @api height;
    twoJsInitialized = false;

    renderedCallback() {
        if (this.twoJsInitialized) {
        this.twoJsInitialized = true;

        loadScript(this, TwoJs)
            .then(() => {
            .catch((error) => {
                console.error(‘Error loading Two.js’, error);

    initializeTwoJs() {
        const container = this.template.querySelector(‘.two-js-container’);
        const two = new Two();

        two.width = this.width || 400;
        two.height = this.height || 300;

        // Use Two.js to create your graphics and animations
        // Example: Create a red circle
        const circle = two.makeCircle(two.width / 2, two.height / 2, 50);
        circle.fill = ‘red’;


In order to load external JavaScript libraries, we need to use the loadScript function of the platform resource loader, this is what allows us to safely import JavaScript in a controlled way.

The loadScript function must be called and handled with a callback, the callback allows the use of methods:

loadScript(this, TwoJs)
.then(() => {
    // Do some logic!
.catch((error) => {
    console.error(‘Error loading Two.js’, error);

In the full example above, we load in Two.js using the loadScript function, we then specify where the drawing area will be (A div with a class name of ‘.two-js-container’) and then we create a red circle to display within the page.

And that is really how simple it is! LWC is much more tolerant of external JavaScript libraries and as long as it is reputable, you can use anything you like.

Thanks for reading,

Daniel Edwards

The Tether Team

#salesforce #salesforcecrm #tethertips #tether #code #3rdparty

Share the Post: