2

Another curious case of empty error messages. This time I am trying to import a JavaScript library, Moment.js, and am getting a failure but no indication of why.

import { loadScript } from "lightning/platformResourceLoader";
import moment from "@salesforce/resourceUrl/moment";

export default class MyComponent extends LightningElement 
{
    renderedCallback()
    {
        Promise.all(
            [
                loadScript(this, moment + '/moment.js')
            ]
        ).then(() =>
            {
                console.log(moment().format());
            }
        )
        .catch(error => 
            {
                console.error("Failed to load moment! ( " + JSON.stringify(error) + " )");
            }
        );
    }
}

The peculiar part of all this, sure it does fail to load, but the error is just... nothing. An empty object. It's an object, not undefined, just with no properties in it whatsoever:

Failed to load moment! ( {} )

The static resource for Moment.js is set up as a zip file (the .js is inside the zip). The static resource cache control is set to public. A coworker used this exact setup for another project and so far no one has found any issues here so I am at a bit of a loss. What would be causing loadScript to fail here, and why would (as unsurprising as it is) I not get any kind of error feedback?

1
1

Using a third-party library with LWC has some rules to be followed due to locker services.

First of the third-party library has to make sure to expose a global function attached to the window object.

I am using the Moment.js found here, and seems perfectly compatible with the Locker.

Now I am not sure why we need Promise.all[] since we are not loading multiple libraries. Simplifying the code to below worked

import { LightningElement } from 'lwc';
import { loadScript } from "lightning/platformResourceLoader";
import moment from "@salesforce/resourceUrl/moment";

export default class Moment extends LightningElement {

momentInitialized = false;

renderedCallback() {
    if (this.momentInitialized) {
        return;
    }
    this.momentInitialized = true;
    loadScript(this, moment)
    .then(() => {
        console.log(window.moment().format());
    })
    .catch(error => {
        console.log(error);
    });
  }
}

I am not using any zip library here and just loaded the javascript file into a static resource. However, if you do put it in the zip file should have no issues.

Also to discover the error it's always better to Enable the Lightning Debug Mode for the user in the sandbox to troubleshoot the actual error.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.