如何在React Native Android中访问BuildConfig产品风味变量

时间:2018-09-14 12:56:14

标签: react-native android-gradle react-native-android android-productflavors android-build-flavors

您好,我点击了以下链接以创建产品风味 enter link description here

我在口味中设置了一个变量,但无法在代码中访问它。

build.gradle。

 productFlavors {
    production {
        minSdkVersion rootProject.ext.minSdkVersion
        applicationId 'com.xxx.production'
        targetSdkVersion rootProject.ext.targetSdkVersion
        resValue "string", "build_config_package", "com.myapp"
        buildConfigField "boolean", "MOCK_VERSION", "false"
        resValue "string", "MOCK_VERSION_ABCD", "false"
    }
    staging {
        minSdkVersion rootProject.ext.minSdkVersion
        applicationId 'com.xxx.staging'
        targetSdkVersion rootProject.ext.targetSdkVersion
        resValue "string", "build_config_package", "com.myapp"
        buildConfigField "boolean", "MOCK_VERSION", "false"
        resValue "string", "MOCK_VERSION_ABCD", "false"
    }
    t3st {
        minSdkVersion rootProject.ext.minSdkVersion
        applicationId 'com.xxx.test'
        targetSdkVersion rootProject.ext.targetSdkVersion
        resValue "string", "build_config_package", "com.myapp"
        buildConfigField "boolean", "MOCK_VERSION", "true"
        resValue "string", "MOCK_VERSION_ABCD", "true"
    }
}

我试图在我的Login.js文件中访问它

import { BuildCofig } from 'react-native';

loginEndpointDecider = () => {
 if(BuildCofig.MOCK_VERSION){
   alert('MOCK_VERSION - true');
 }else{
   alert('MOCK_VERSION - false');
 }
}

要运行该应用程序

react-native run-android --variant=stagingDebug

我正在尝试访问buildConfigField MOCK_VERSION

请您提出如何使它工作的建议。

谢谢 R

1 个答案:

答案 0 :(得分:1)

为此,我使用了react-native-build-config。效果很好,但是请记住为使用proguard的生成的BuildConfig类设置保留规则。启发了该库react-native-config的框架也可以工作,但是当目标> = 0.56 RN时,我在配置该库与cocoapods时遇到问题。