Many modern-day applications now go through different stages of the product
cycle such as development, staging, production etc.
Having different environment variables for each environment will make it a lot
easier to manage any application. This article is intended to share one solution
to address this problem in React Native. We will be using a library called
react-native-config for this
purpose; you can also try
react-native-dotenv.
We will be focusing on having three different bundles containing configuration
files for development, staging and production environments.
Installing react-native-config
Install the package:
For iOS also run pod install
after package is installed.
Setup for Android
Add below line of code to android/app/build.gradle
to apply plugin.
Create three files in root folder of the project .env.development
,
.env.staging
& .env.production
which will contain our environment variables.
Now we need to define envConfigFiles
in build.gradle
associating builds with
env files. To achieve this, add the below code before the apply from
call,
and be sure to leave the build cases in lowercase.
Next, add productFlavors
in build.gradle
, just below buildTypes
.
Names should match based on productFlavors
, so productiondebug
will match
debug
in this case and generate debug build of App with configuration from
.env.production
.
Also add matchingFallbacks
in buildTypes
as shown below:
Add the below scripts to scripts
in the package.json
file.
Now, to have a debug build with staging environment, run:
Or, to have a release build with staging environment, run:
Setup for iOS
In iOS we will create three new schemes TestAppDevelopment
, TestAppStaging
&
TestAppProduction
containing configuration files for development, staging and
production environments respectively.
To create schemes, open the project in xcode & do the following:
In the Xcode menu, go to Product > Scheme > Edit Scheme.
Click Duplicate Scheme on the bottom and name it TestAppDevelopment
and check
the shared
checkbox.
We will repeat the above steps two more times (for TestAppStaging
&
TestAppProduction
).
Now edit the newly generated scheme. Expand "Build" settings and click
"Pre-actions", and under the plus sign select "New Run Script Action". Select
project from the Provide build settings from
dropdown.
Where it says "Type a script or drag a script file", type:
Add the below scripts to scripts
in the package.json
file.
Now, to have a build with staging environment, run:
And it will run the application with staging configuration.
Accessing environment variables
Once the setup is complete, we can access the variables as shown below: