Kitwradr
Kitwradr

Reputation: 2178

How can we do dynamic imports of Npm modules in React?

I have seen the webpack documentation for dynamic imports (refer below image), but this doesn't seem to work in react as we return components directly in React rather than adding elements to DOM (after then() of the promise).

In React lazy loading documentation, they have shown how to lazy load only other React components but not how to dynamic import NPM libraries.

So if someone could explain how to dynamic import npm modules, that would be great.

enter image description here

Upvotes: 0

Views: 5733

Answers (2)

Shan
Shan

Reputation: 1568

Your code is working fine as expected. However this will include the whole lodash library into the bundle since lodash is a cjs module. You can import the particular module which is required like below to avoid including whole lodash lib,

function getComponent() {
  return import("lodash/join")
    .then(({ default: _ }) => {
      const element = document.createElement("div");
      element.innerHTML = _(["Hello", "world"], " ");
      return element;
    })
    .catch((err) => "error");
}

In case if you want to use more functions like join from lodash, you could use lodash-es which is a esm module and tree shakeable, webpack will include only the imported functions to your bundle.

function getComponent() {
  return import("lodash-es")
    .then(({ join, reverse }) => {
      const element = document.createElement("div");
      const txtArr = ["Hello", "world"]
      element.innerHTML = join(reverse(txtArr), " ");
      return element;
    })
    .catch((err) => "error");
}

Edit eloquent-forest-bxgrvu

Upvotes: 1

Mohammad Esam
Mohammad Esam

Reputation: 502

the NPM package imports follow it is component, so if we dynamically imported the component that means we dynamically imported the Package, since the import does not get called until it is component gets called

For further information about code splitting read this article it goes throw all the techniques you can use to achieve code splitting

https://blog.logrocket.com/react-dynamic-imports-route-centric-code-splitting-guide/

Upvotes: 1

Related Questions