-1

I have a plain javascript website. I'm importing with webpack a react component and use it in the website. The problem is the component only works if I import react(globally). I only use this component once in a while so I only want to import react if needed. I'm interested in such a thing: if(some_condition){ import react and import my component} How could I do this? Thanks

Shali
  • 41
  • 1
  • 5
  • https://stackoverflow.com/questions/36367532/how-can-i-conditionally-import-an-es6-module – Evren Mar 14 '21 at 17:10

2 Answers2

0

You can do dynamic imports like this:

(async () => {
  if (somethingIsTrue) {
    import('/modules/my-module.js')
      .then((module) => {
      // Do something with the module.
    });
  }
})();

Source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports

emilytrabert
  • 137
  • 1
  • 1
  • 7
0

You can use dynamic import.

if (condition) {
  Promise.all([
    import("react-dom"),
    import("react"),
    import("path/to/component"),
  ])
    // if you use named export for component, just use name instead of `default`
    .then(([{ render }, { createElement }, { default: Component }]) => {
      // select element where you want to render
      let root = document.getElementById("root");
      // render your component
      render(createElement(Component), root);
    });
}
Mr. Hedgehog
  • 2,644
  • 1
  • 14
  • 18