Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can you conditionally import files in react native?

Situation: I'm working on a react native project with different versions for the same app. To do this I'm using app flavors for android and for iOS I will be using build targets. I've already made a native android module that can return the android build flavor that is being used. My goal is to be able to import a different React component to display for each flavor.

Problem: My original idea was to conditionally import the React Native component to display for each flavor, but I've come to understand that conditional imports aren't a thing in JavaScript and they have to be at the top level scope. Is there a way to tackle this problem without importing every file for every build? (I want to avoid making the binary larger by importing components that are only being used in other flavors of the app).

What I want to do:

import { NativeModules } from 'react-native';

var appFlavor;

NativeModules.RNVariantsLib.getBuildFlavor((err ,flavor) => {
  console.log('flavor ' + flavor);
  appFlavor = flavor;
});

if(appFlavor == 'flavorA'){
  import Component from './a';
}
if(appFlavor == 'flavorB'){
  import Component from './b';
}

export default Component;
like image 760
user3512797 Avatar asked Mar 23 '26 19:03

user3512797


1 Answers

You could try with require

let Component = null;
if(appFlavor == 'flavorA'){
  Component = require('./a');
}
if(appFlavor == 'flavorB'){
  Component = require('./b');
}

export default Component;
like image 198
Tuan Luong Avatar answered Mar 26 '26 08:03

Tuan Luong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!