我正在使用react-native来构建一个跨平台的应用程序,但我不知道如何设置环境变量,以便我可以有不同的常量为不同的环境。

例子:

development: 
  BASE_URL: '',
  API_KEY: '',
staging: 
  BASE_URL: '',
  API_KEY: '',
production:
  BASE_URL: '',
  API_KEY: '',

当前回答

遵循以下步骤

NPM安装react-native-dotenv 用一些变量名设置。env文件,例如APP_NAME="my-app" 修改bable.config.js

模块。出口= { 预设:['模块:metro-react-native-babel-preset '), 插件:[ ["模块:react-native-dotenv ", { :“envName APP_ENV”, :“moduleName @env”, “路径”:“.env”, “安全”:假的, “allowUndefined”:没错, “详细”:假的 }) ] };

重新启动所有应用程序 尝试从“@env”导入{APP_NAME}。如果这不起作用,那么执行这个const APP_NAME = process.env['APP_NAME'];

欢呼:)

其他回答

对于最新的RN版本,您可以使用这个本机模块:https://github.com/luggit/react-native-config

我已经为相同的问题创建了一个预构建脚本,因为我需要一些不同环境的不同API端点

const fs = require('fs')

let endPoint

if (process.env.MY_ENV === 'dev') {
  endPoint = 'http://my-api-dev/api/v1'
} else if (process.env.MY_ENV === 'test') {
  endPoint = 'http://127.0.0.1:7001'
} else {
  endPoint = 'http://my-api-pro/api/v1'
}

let template = `
export default {
  API_URL: '${endPoint}',
  DEVICE_FINGERPRINT: Math.random().toString(36).slice(2)
}
`

fs.writeFile('./src/constants/config.js', template, function (err) {
  if (err) {
    return console.log(err)
  }

  console.log('Configuration file has generated')
})

我已经创建了一个自定义的npm运行脚本来执行反应本机运行..

我package-json

"scripts": {
    "start-ios": "node config-generator.js && react-native run-ios",
    "build-ios": "node config-generator.js && react-native run-ios --configuration Release",
    "start-android": "node config-generator.js && react-native run-android",
    "build-android": "node config-generator.js && cd android/ && ./gradlew assembleRelease",
    ...
}

然后在我的服务组件中导入自动生成的文件:

import config from '../constants/config'

fetch(`${config.API_URL}/login`, params)

@chapinkapa的回答很好。由于Mobile Center不支持环境变量,我采取的一种方法是通过本地模块公开构建配置:

在android上:

   @Override
    public Map<String, Object> getConstants() {
        final Map<String, Object> constants = new HashMap<>();
        String buildConfig = BuildConfig.BUILD_TYPE.toLowerCase();
        constants.put("ENVIRONMENT", buildConfig);
        return constants;
    } 

或者在ios上:

  override func constantsToExport() -> [String: Any]! {
    // debug/ staging / release
    // on android, I can tell the build config used, but here I use bundle name
    let STAGING = "staging"
    let DEBUG = "debug"

    var environment = "release"
    if let bundleIdentifier: String = Bundle.main.bundleIdentifier {
      if (bundleIdentifier.lowercased().hasSuffix(STAGING)) {
        environment = STAGING
      } else if (bundleIdentifier.lowercased().hasSuffix(DEBUG)){
        environment = DEBUG
      }
    }

    return ["ENVIRONMENT": environment]
  }

您可以同步读取构建配置,并在Javascript中决定如何执行。

与其硬编码你的应用常量并在环境上进行切换(我将在稍后解释如何做到这一点),我建议使用12因素建议,让你的构建过程定义你的BASE_URL和API_KEY。

要回答如何将您的环境暴露为react-native,我建议使用Babel的Babel -plug -transform-inline-environment-variables。

为了让它工作,你需要下载这个插件,然后你需要设置一个.babelrc,它应该看起来像这样:

{
  "presets": ["react-native"],
  "plugins": [
    "transform-inline-environment-variables"
  ]
}

因此,如果你通过运行API_KEY=my-app-id react-native bundle(或start, run-ios,或run-android)来编译你的react-native代码,那么你所要做的就是让你的代码看起来像这样:

const apiKey = process.env['API_KEY'];

然后巴别塔会用:

const apiKey = 'my-app-id';

为了解决这个问题,我使用了react-native中内置的__DEV__ polyfill。只要您不是为生产构建react native,它就会自动设置为true。

例如:

//vars.js

let url, publicKey;
if (__DEV__) {
  url = ...
  publicKey = ...
} else {
  url = ...
  publicKey = ...
}

export {url, publicKey}

然后只需导入{url}从'../vars',你总是会得到正确的。不幸的是,如果你想要两个以上的环境,这就行不通了,但它很简单,而且不需要向你的项目添加更多的依赖项。