[SalesForce] Import ES modules in LWC

I have a JS library that provides a module.
I am importing it in my LWC like this example here: https://developer.salesforce.com/docs/component-library/documentation/lwc/lwc.create_third_party_library

Sadly, there is no example on how to import d3 (if you look carefully you can see SF only import D3 in caps to reference resource, not the lib, and just rely on d3 being global).

I tried importing from 'libname' but i get the error that this is not a known LWC module.

If i try to import from resource/libname, i get the below.

Invalid reference Resource/somelib.min.js of type resourceUrl in file myComponent.js

(Example module to try: https://github.com/flatpickr/flatpickr)

Without it everything works save for Intellisense in VS code and pesky warnings about functions being undefined.

EDIT the code works fine. I am asking how to get symbols into my code.

Best Answer

The LWC compiler only resolves absolute import with the following form: <namespace-name>/<lwc-module-name>. Because of this, you can't directly import an NPM module via import d3 from 'd3';.

You have 2 options if you want to consume an es module from an lwc component:

  • create a new lwc module (e.g. d3 with a d3.js) and then import your module from your lwc component via the standard import syntax: import d3 from 'c/d3'; (lwc-recipe). This approach should be avoided for large modules because they are sent and evaluated with your component and can create some performance issues.

  • transform your es module to the UMD format and load it via a static resource (lwc-recipe). If the library attaches properties on the window object you should add them as globals to your .eslintrc.json to avoid linting errors.

Related Topic