2

I am trying to use Luxon in a LWC.

I believe I am messing up the syntax of the decomposition of DateTime from the library.

Following the documentation: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.js_third_party_library

My Steps

I started by downloading Luxon from GitHub: https://github.com/moment/luxon

I extracted luxon-master.zip and rezipped the /src directory.

I renamed the .zip "luxon". I uploaded this to static resources as "Luxon".

My Import:

import DateTime from '@salesforce/resourceUrl/Luxon';
import {loadScript} from 'lightning/platformResourceLoader';

renderedCallback()

renderedCallback() {
    loadScript(this, DateTime + '/luxon.js')
.then(() => { /* callback */ });
}

Use Luxon DateTime

get luxonDate() {
    return DateTime.now().toISO();
}
4

As an import, you need to attach Luxon to the window element to get it. Change the very first part from:

var luxon = ... 

To:

window.luxon = ...

Or, alternatively, you can add a line at the end:

window.luxon = luxon

Next, you need to reference it in your code, so:

return luxon.DateTime.now().toISO();

You can also convert this script to a "native" ES6 script.

Instead of attaching luxon to window, create a new LWC called luxon, delete the .html file, copy the luxon source to the .js file, and add this as the very last line:

const DateTime = luxon.DateTime;
export { DateTime };

Then you can use it in your script directly:

import DateTime from 'c/luxon';

...

return DateTime.now().toISO();

Functional Example

You can also choose to export luxon, and use it as above (e.g. luxon.DateTime...) or each individual part that you need.


Edit: I also see that they have an ES6 module. This would be a copy-paste scenario, you can use it verbatim with no modifications.

2
  • I could only import Luxon as a single js file by changing the first declaration on the library file from var luxon= to window.luxon=. Any ideas on how to import it without modifying its source code? I couldn't understand your first example (how would I assign it to window.luxon if I can't even reference it?) Oct 2 at 1:59
  • 1
    @RenatoOliveira See this. LWC uses "strict mode," which among other things, doesn't allow var luxon to become a global, thus unusable outside of the source file. Your two basic choices are: modify luxon source to attach to window.luxon, or use the ES6 module, as demonstrated in the link.
    – sfdcfox
    Oct 2 at 3:55

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.