React Native Expo 环境变量

Ash*_*rth 8 environment-variables react-native expo

所以我对本文和其他文章中解释的环境变量的概念感到满意 https://www.freecodecamp.org/news/how-to-gracefully-use-environment-variables-in-a-react-native-应用程序/

太好了,我已经存储了我的 SOMETHING="something" 所以我可以使用 env.SOMETHING 或其他任何东西

我有点迷失的部分是您保存实时变量的位置

我宁愿不做这样的解决方案,因为看起来您仍然将密钥公开,并且您只是根据环境使用 if 语句进行选择

使用 expo react native 管理环境

例如,对于我们拥有的 Express App 部署,我们指定

let endPointURL = env.endPointURL
Run Code Online (Sandbox Code Playgroud)

然后我们保持versoin变量本地的,当它坐在与AWS它是由AWS服务器,解释覆盖这里

我只是想知道 Android 和 iOS 版本(在各自的商店中)或通过 Expo 是否存在类似的东西?

谢谢大家

Cal*_*ort 13

老实说,我认为他们的做法有点愚蠢。可能有比这更好的方法,但我想我遵循了他们的文档建议。

https://docs.expo.io/versions/latest/distribution/release-channels/#using-release-channels-for-environment-variable-configuration

他们有一个代码片段,建议您创建一个函数来查看发布配置本身。

我的解释是,您可能会执行类似于下面的代码的操作,并将您的环境变量存储在一个variables.js文件中,然后将您的环境变量拉入其中。

import Constants from 'expo-constants';

export const prodUrl = "https://someapp.herokuapp.com";

const ENV = {
  dev: {
    apiUrl: "http://localhost:3000"
  },
  staging: {
    apiUrl: prodUrl
  },
  prod: {
    apiUrl: prodUrl
  }
};

function getEnvVars(env = "") {
  if (env === null || env === undefined || env === "") return ENV.dev;
  if (env.indexOf("dev") !== -1) return ENV.dev;
  if (env.indexOf("staging") !== -1) return ENV.staging;
  if (env.indexOf("prod") !== -1) return ENV.prod;
}

export default getEnvVars(Constants.manifest.releaseChannel);

Run Code Online (Sandbox Code Playgroud)

编辑:

现在 Expo 支持配置文件为app.config.jsor app.config.ts,我们可以使用dotenv. 检查这个:https : //docs.expo.io/guides/environment-variables/#using-a-dotenv-file

  • 经过(长时间!)深入研究如何完成此操作后,我将选择您的答案@Caleb。遗憾的是没有更简单的机制来实现这一点!我最终保留了两个文件夹 - 一个用于 live,一个用于 dev,还有一个用于环境变量的不同文件夹,我只是 git push 和 pull 来保持源代码最新。非常愚蠢地说它有效!:'D (2认同)

小智 5

一种更简单的方法是导出 env 对象而不是函数:

import Constants from 'expo-constants';
import { Platform } from "react-native";

const localhost =
 Platform.OS === "ios" ? "localhost:8080" : "10.0.2.2:8080";


const ENV = {
    dev: {
      apiUrl: localhost,
      amplitudeApiKey: null,
    },
    staging: {
      apiUrl: "[your.staging.api.here]",
      amplitudeApiKey: "[Enter your key here]",
      // Add other keys you want here
    },
    prod: {
      apiUrl: "[your.production.api.here]",
      amplitudeApiKey: "[Enter your key here]",
      // Add other keys you want here
    }
};

const getEnvVars = (env = Constants.manifest.releaseChannel) => {
  if (env === null || env === undefined || env === "" || env.indexOf("dev") !== -1) return ENV.dev;
  if (env.indexOf("staging") !== -1) return ENV.staging;
  if (env.indexOf("prod") !== -1) return ENV.prod;
}

const selectedENV = getEnvVars();

export default selectedENV;
Run Code Online (Sandbox Code Playgroud)

// Import
import env from '..xxx/utility/env';
Run Code Online (Sandbox Code Playgroud)