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

例子:

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

当前回答

我已经为相同的问题创建了一个预构建脚本,因为我需要一些不同环境的不同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)

其他回答

在我看来,最好的选择是使用react-native-config。 支持12因子。

我发现这个包非常有用。您可以设置多个环境,例如开发、登台、生产。

在Android的情况下,变量也可以在Java类,gradle, AndroidManifest.xml等。 在iOS中,变量也可以在Obj-C类,Info.plist中使用。

你只需要创建文件

.env.development .env.staging .env.production

你用键和值填充这些文件,比如

API_URL=https://myapi.com
GOOGLE_MAPS_API_KEY=abcdefgh

然后使用它:

import Config from 'react-native-config'

Config.API_URL  // 'https://myapi.com'
Config.GOOGLE_MAPS_API_KEY  // 'abcdefgh'

如果你想使用不同的环境,你基本上像这样设置ENVFILE变量:

ENVFILE=.env.staging react-native run-android

或者为生产组装应用程序(在我的情况下是android):

cd android && ENVFILE=.env.production ./gradlew assembleRelease

可以使用process.env.blabla而不是process.env['blabla']访问变量。我最近让它工作,并评论了我是如何在GitHub上的一个问题上做到这一点的,因为我有一些基于公认答案的缓存问题。问题是这样的。

如果你使用的是Expo,根据文档https://docs.expo.io/guides/environment-variables/有两种方法

方法#1 -在应用程序清单(app.json)中使用.extra道具:

在你的app.json文件中

{
  expo: {
    "slug": "my-app",
    "name": "My App",
    "version": "0.10.0",
    "extra": {
      "myVariable": "foo"
    }
  }
}

然后要访问你的代码(即App.js)上的数据,只需导入expo-constants:

import Constants from 'expo-constants';

export const Sample = (props) => (
  <View>
    <Text>{Constants.manifest.extra.myVariable}</Text>
  </View>
);

这个选项是一个很好的内置选项,不需要安装任何其他包。

方法#2 -使用Babel“替换”变量。这是您可能需要的方法,特别是当您正在使用裸工作流时。其他的答案已经提到了如何使用babel-plugin-transform-inline-environment-variables来实现它,但是我将在这里留下一个官方文档的链接来说明如何实现它:https://docs.expo.io/guides/environment-variables/#using-babel-to-replace-variables

[来源]从我的发现来看,默认情况下,它只可能做生产和开发配置(没有登台或其他环境)-对吗?

现在,我一直在使用一个environment.js文件,可以用来检测博览会发布通道,并根据此更改返回的变量,但对于构建,我需要更新返回的非DEV变量为staging或prod:

import { Constants } from 'expo';
import { Platform } from 'react-native';
const localhost = Platform.OS === 'ios' ? 'http://localhost:4000/' : 'http://10.0.2.2:4000/';
const ENV = {
  dev: {
    apiUrl: localhost,
  },
  staging: {
    apiUrl: 'https://your-staging-api-url-here.com/'
  },
  prod: {
    apiUrl: 'https://your-prod-api-url-here.com/'
  },
}
const getEnvVars = (env = Constants.manifest.releaseChannel) => {
  // What is __DEV__ ?
  // This variable is set to true when react-native is running in Dev mode.
  // __DEV__ is true when run locally, but false when published.
  if (__DEV__) {
    return ENV.dev;
  } else {
    // When publishing to production, change this to `ENV.prod` before running an `expo build`
    return ENV.staging;
  }
}
export default getEnvVars;

选择

谁有在用expo构建的项目中使用react-native-dotenv的经验?我很想听听你的想法

https://github.com/goatandsheep/react-native-dotenv

步骤1:像这样创建单独的组件 组件名称:pagebase.js 步骤2:在此使用代码this

    export const BASE_URL = "http://192.168.10.10:4848/";
    export const API_KEY = 'key_token';

步骤3:在任何组件中使用它,要使用它,首先导入这个组件,然后使用它。 导入并使用它:

        import * as base from "./pagebase";

        base.BASE_URL
        base.API_KEY