Implement dynamic module import in React Native Expo
P粉885562567
2023-08-28 15:01:05
<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>
You can use the import() function to load modules asynchronously. Here is an example:
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.