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

例子:

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

当前回答

我使用react-native-config为我的项目设置了多个环境。README文件非常清楚地解释了如何在项目中配置库。只要确保实现Android部分的额外步骤即可。

另外,在设置多个环境时,请确保在包中指定正确的启动命令。Json,基于您的系统终端。我在windows笔记本电脑中开发了Android代码,在Macbook中开发了iOS代码,所以我各自的启动命令都在包中。Json是-

"scripts": {
        "android:dev": "SET ENVFILE=.env.dev && react-native run-android",
        "android:prod": "SET ENVFILE=.env.prod && react-native run-android",
        "ios:dev": "ENVFILE=.env.dev react-native run-ios",
        "ios:prod": "ENVFILE=.env.prod react-native run-ios",
},

如果您只需要维护一个.env文件,请考虑使用 react-native-dotenv是一个较轻的选择,尽管我在为这个库设置多个.env文件时遇到了一些问题。

其他回答

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

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

如果你正在使用expo(managed workflow)开发你的应用程序,你必须在你的项目的根目录中创建一个名为app.config.js的文件,并将以下代码添加到文件中:

const myValue = "My App";

export default () => {
    if (process.env.MY_ENVIRONMENT === "development") {
        return {
            name: myValue,
            version: "1.0.0",
            // All values in extra will be passed to your app.
            extra: {
                fact: "dogs are cool"
            }
        };
    } else {
        return {
            name: myValue,
            version: "1.0.0",
            // All values in extra will be passed to your app.
            extra: {
                fact: "kittens are cool"
            }
        };
    }
};

然后你应该使用下面的命令启动/发布你的应用程序(这在Windows中也适用)。对于其他操作系统,请阅读我在最后提到的文章)。

npx cross-env MY_ENVIRONMENT=开发博览会启动/发布

这将使用上面提到的环境变量(MY_ENVIRONMENT)启动或发布应用程序。应用程序将根据环境变量加载适当的配置。现在可以通过将名为exo -constants的模块导入到项目文件中,从配置中访问变量extra。例如:

import Constants from "expo-constants";

export default function App() {
    console.log(Constants.manifest.extra.fact);
    return (
        <>
            <View>
                <Text>Dummy</Text>
            </View>
        </>
    );
}

使用常数。Manifest我们可以额外访问里面的对象。因此,如果您的环境变量是development,这段代码应该console.log“dogs are cool”。我希望这对你有用。要了解更多信息,请阅读本文。

遵循以下步骤

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'];

欢呼:)

你也可以有不同的env脚本:production.env.sh development.env.sh production.env.sh

然后在开始工作时将它们来源[这只是绑定到一个别名] 所以所有的sh文件都导出了每个env变量:

export SOME_VAR=1234
export SOME_OTHER=abc

然后添加babel-plugin-transform-inline-environment-variables将允许在代码中访问它们:

export const SOME_VAR: ?string = process.env.SOME_VAR;
export const SOME_OTHER: ?string = process.env.SOME_OTHER;