Lightning Web Components – Fix TypeError When Using LWCC Chart.Js in LWR Experience Cloud Site

chartjsexperience-cloudlightning-web-componentslwr

Imported open-source LWCC Chart.js from Salesforce Labs and made no changes. Chart works fine in standard scratch org Lightning Page but when try same component in an LWR Experience Cloud site from same scratch org getting error below.

Want to ensure not an LWR Experience Cloud limitation. A lot of the Chart.js construction is contained in a Static Resource and is pretty difficult to decipher for me. Other similar posts on topic seem too old to be relevant.

TypeError: window.Chart is not a constructor at Proxy.drawChart (modules/prov/chart.js:1:6528) at i.eval [as job] (modules/prov/chart.js:1:5332) at eval (modules/prov/reactivityManager.js:1:285) at eval (eval at LL (https://page-app-1307.scratch.my.site.com/webruntime/framework/f2fdf217e4/prod/lwr_bootstrap_locker:19:100), <anonymous>:5:19017) at M.St (https://page-app-1307.scratch.my.site.com/webruntime/framework/f2fdf217e4/prod/lwr_bootstrap_locker:17:2803) at M.<anonymous> (https://page-app-1307.scratch.my.site.com/webruntime/framework/f2fdf217e4/prod/lwr_bootstrap_locker:17:2242)

Best Answer

There is a known limitation of Lightning Locker in LWR sites where the scripts loaded through lightning/platformResourceLoader run in system mode outside of a Lightning Locker sandbox. As a result, the component loading the script doesn’t have access to the same global variable scope as the script itself, preventing it from accessing any global variable set by the script. You can read about it in the documentation as well.

To get around this restriction, we need to implement our own loadScript function. I have created a Pull Request on the LWC Recipes repo that adds this custom implementation to the recipes, and shows its usage in components like libsD3, libsChartjs, and libsFullCalendar.

Please add the resourceLoader component from this Pull Request to your codebase, and use the below import statement to use the loadScript function from the custom resourceLoader module instead of the standard lightning/platformResourceLoader module.

import { loadScript } from 'c/resourceLoader';
Related Topic