9

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.

2
  • 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
    Commented Mar 7, 2019 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
    Commented Mar 7, 2019 at 5:56

1 Answer 1

19

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.

2
  • 3
    Would be interesting to see a deeper dive blog article on the pros/cons of these two import options and what the considerations are for each. (e.g. What is considered a "large" module and how does it impact performance in different use cases? Are there advantages to one or the other if the same module is used in a bunch of components on a page?) Commented Oct 17, 2020 at 15:19
  • Hi @pmdartus, could you please detail this answer with a 3rd bullet point and example to show how to import an LWC module from a 2GP namespaced package, now that this is deemed possible with LWS (cf developer.salesforce.com/docs/component-library/documentation/…) ?
    – altius_rup
    Commented Oct 25, 2022 at 8:40

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .