Config variables for React Native apps in Android
Module to expose config variables set in Gradle to your javascript code in React Native.
Bringing some 12 factor love to your mobile apps.
Usage
Declare config variables in Gradle, under android/app/build.gradle
:
android {
defaultConfig {
buildConfigField "String", "API_URL", '"https://myapi.com"'
buildConfigField "Boolean", "SHOW_ERRORS", "true"
...
Then access those from javascript:
var Config = ; ConfigAPI_URL // "https://myapi.com"ConfigSHOW_ERRORS // true
More on Gradle and configs
In case you're wondering how to keep secrets outside your source: create android/config.properties
:
API_URL="https://:secret@myapi.com"
Then load it from build.gradle
like:
defaultConfig {
def props = new Properties()
props.load(new FileInputStream(rootProject.file('config.properties')))
props.each { key, val -> buildConfigField "String", key, val }
}
You can do something similar under release in buildTypes
to read a different set of credentials from another file.
Setup
- Include this module in
android/settings.gradle
:
include ':react-native-android-config'
include ':app'
project(':react-native-android-config').projectDir = new File(rootProject.projectDir,
'../node_modules/react-native-android-config/android')
- Add a dependency to your app build in
android/app/build.gradle
:
dependencies {
...
compile project(':react-native-android-config')
}
- Change your main activity to add a new package, in
android/app/src/main/.../MainActivity.java
:
// add import