4

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.

  • Could you clarify a bit - are you trying to find out how d3 is being utilized or you are trying to import another 3rd party JS and would like to understand how to do that? – Jayant Das Mar 7 at 3:43
  • I want to understand how to use es-module import x from ‘myscript’; in lwc to avoid ‘undefined’ red squigglies in vs code. – zaitsman Mar 7 at 5:56
8

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.

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.