Home  >  Q&A  >  body text

Implement dynamic module import in React Native Expo

<p>If my <strong>React Native</strong> Expo app (running within an Expo Go app) currently does an <code>import/from</code></p> <pre class="brush:php;toolbar:false;">import Foo, {Bar} from "foo";</pre> <p>How can I convert this into a dynamic import that only imports when a certain condition is met, such as when <code>hello === "world"</code>? </p> <p>The following actions will cause the application to crash with the error <code>non-std C exception</code>. </p> <pre class="brush:php;toolbar:false;">if (hello === "world") { import Foo, {Bar} from "foo"; }</pre> <p>Tried the following workaround but still results in a crash with <code>non-std C exception</code>: </p> <pre class="brush:php;toolbar:false;">if (hello === "world") { const Foo = import('foo') const Bar = Foo.Bar }</pre></p>
P粉885562567P粉885562567418 days ago504

reply all(1)I'll reply

  • P粉744691205

    P粉7446912052023-08-29 09:13:52

    You can use the import() function to load modules asynchronously. Here is an example:

    let Foo;
    let Bar;
    
    if (hello === "world") {
      import("foo").then((module) => {
        Foo = module.default;
        Bar = module.Bar;
      });
    }

    In this code, the import() function returns a promise that resolves to a module object. The default property of the module object is assigned to the Foo variable, and the Bar property of the module object is assigned to the Bar variable.

    It should be noted that the import() function is asynchronous, so any code that relies on imported modules should be placed in the then() callback function. Additionally, you should ensure that any code that relies on imported modules is only executed after the module has been loaded.

    reply
    0
  • Cancelreply