Lightning Web Components and shared third-party JavaScript libraries

If you are planning to use a third-party JavaScript library in Lightning Web Components, there is a behavior you have to be aware of: you get an undefined error when you try to load a JavaScript library that has already been loaded by another component.
This can happen for example in a Salesforce community that includes two or more Lightning Web Components using the same external library.

It’s important to note that this behaviour is different to the one in Aura components. In Aura, you can specify the same JavaScript library multiple times without any problem. Please note though, that an undefined error can also happen in a Lightning Web Component that tries to load a library that an Aura component previously loaded.

In my case the JavaScript library that was generating this error was Highcharts.

The following code generates an undefined error if highcharts713.js has already been loaded:

[prism field=lwc-jslib-code1 language=Java]

The solution to this problem (thanks to my colleague Tom for his help in solving this problem) is to check if Highcharts is already available before trying to load it:

[prism field=lwc-jslib-code2 language=javascript]

You can find more information on using third-party libraries both on Lightning Web Components and Aura components here:

Lightning Web Component: Use Third-Party JavaScript Libraries

Aura component: Require

greg-rakozy-vw3Ahg4x1tY-unsplash
By Edith Valencia-Martinez
31 October 2019
Application DevelopmentSalesforceSalesforce DevelopmentThe Dev ZoneThe Good Systems Blog

Share this post

Catt to action

Amet aliquam id diam maecenas ultricies mi eget mauris

Lorem ipsum dolor sit amet, consectetur elit tellus, luctus nec ullamcorper mattis, pulvinar dapibus leo.