2

I have created a LWC component that loads a third party library from a static resource.

Here's an example of the library:

window.myLib = (function() {
    return {
        myFunction: function(a, b) {
            return a * b;
        }
    };
}());

Once the library is loaded, I should be able to access the library in the parent web component through the following syntax:

Promise.all([
    loadScript(this, library +   '/script.js'),
]).then(() => {
   //This works when the component is loaded internally (e.g. embedded on a record)
   let result = myLib.myFunction(2,2);
   debug('Results', result);
   //This also works when the component is loaded internally
   let result = window.myLib.myFunction(2,2);
   debug('Results', result);
}).catch(err => {
    debug('Failed to load full calendar', err?.message);
});

However, the issue I am facing is that when the LWC component is embedded in a Build Your Own (LWR) Digital Experience, the script throws an error "myLib is undefined".

Setup:

  • Lightning Web Security is enabled (instead of Lightning Locker)

What is peculiar is that upon logging the "window" object, we can see in the console that the window object contains our library, however attempting to directly access the global function "myFunction" returns as undefined.

//The chrome console reports that there is a property "myLib" on window
console.log(window)
//Output is undefined
console.log(typeof myLib)
//Output is undefined
console.log(window.myLib)
//Error thrown "cannot read property myFunction of undefined 
console.log(window.myLib.myFunction)

What we tried so far:

  • renderMode = 'light'; on the web component

  • converting the library to UMD format

  • converting the library to a module

  • added an exception in the .eslintrc.json file for our library that looks like this:

    { "globals": { "myLib":true } }

  • placed the .eslintrc.json in the lwc folder

  • placed the .eslintrc.json in the root project directory

  • updated the package.json to add global lint exception

    "eslintConfig": { "globals": { "FullCalendar": true } }

  • added /* global myLib */ to the header of the LWC class

Our observation is that this is LWR specific issue as we are using the same library for our internal facing LWC components. Has anyone dealt with a similar issue?

  • What I would say is that since both Locker Service and LWS provide namespace scoped "secure" wrappers for `window`, perhaps explicitly referencing `window` is a bad idea. From what I recall, `loadScript` actually loads the scripting in some wrapper, but I've not used third partly libs in LWCs since first experimenting with LWCs back in 2019. – Phil W May 12 '23 at 07:44

0 Answers0