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

例子:

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

当前回答

经过长时间的努力,我意识到react-native并没有正式提供这个功能。这是在babel生态系统中,所以我应该学习如何写一个babel插件…

/**
 * A simple replace text plugin in babel, such as `webpack.DefinePlugin`
 * 
 * Docs: https://github.com/jamiebuilds/babel-handbook
 */
function definePlugin({ types: t }) {
    const regExclude = /node_modules/;
    return {
        visitor: {
            Identifier(path, state) {
                const { node, parent, scope } = path;
                const { filename, opts } = state;
                const key = node.name;
                const value = opts[key];

                if (key === 'constructor' || value === undefined) { // don't replace
                    return;
                }
                if (t.isMemberExpression(parent)) { // not {"__DEV__":name}
                    return;
                }
                if (t.isObjectProperty(parent) && parent.value !== node) { // error
                    return;
                }
                if (scope.getBinding(key)) { // should in global
                    return;
                }
                if (regExclude.test(filename)) { // exclude node_modules
                    return;
                }
                switch (typeof value) {
                    case 'boolean':
                        path.replaceWith(t.booleanLiteral(value));
                        break;
                    case 'string':
                        path.replaceWith(t.stringLiteral(value));
                        break;
                    default:
                        console.warn('definePlugin only support string/boolean, so `%s` will not be replaced', key);
                        break;
                }
            },
        },
    };
}

module.exports = definePlugin;

就这样,然后你可以这样用:

module.exports = {
    presets: [],
    plugins: [
        [require('./definePlugin.js'), {
            // your environments...
            __DEV__: true,
            __URL__: 'https://example.org',
        }],
    ],
};

回答者提到的包也很棒,我也参考了metro-transform-plugins/src/inline-plugin.js。

其他回答

我使用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文件时遇到了一些问题。

如果你使用的是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

React native没有全局变量的概念。 它严格执行模块化范围,以促进组件的模块化和可重用性。

但是,有时您需要组件能够感知它们所处的环境。在这种情况下,定义一个环境模块非常简单,然后组件可以调用它来获取环境变量,例如:

environment.js

var _Environments = {
    production:  {BASE_URL: '', API_KEY: ''},
    staging:     {BASE_URL: '', API_KEY: ''},
    development: {BASE_URL: '', API_KEY: ''},
}

function getEnvironment() {
    // Insert logic here to get the current platform (e.g. staging, production, etc)
    var platform = getPlatform()

    // ...now return the correct environment
    return _Environments[platform]
}

var Environment = getEnvironment()
module.exports = Environment

my-component.js

var Environment = require('./environment.js')

...somewhere in your code...
var url = Environment.BASE_URL

这创建了一个单例环境,可以从应用范围内的任何地方访问。你必须显式地要求(…)使用环境变量的任何组件的模块,但这是一件好事。

我使用babel-plugin-transform-inline-environment-variables。

我所做的是将配置文件放在S3中的不同环境中。

s3://example-bucket/dev-env.sh
s3://example-bucket/prod-env.sh
s3://example-bucket/stage-env.sh

每个env文件:

FIRSTENV=FIRSTVALUE
SECONDENV=SECONDVALUE

之后,我在包中添加了一个新脚本。Json,它运行用于捆绑的脚本

if [ "$ENV" == "production" ]
then
  eval $(aws s3 cp s3://example-bucket/prod-env.sh - | sed 's/^/export /')
elif [ "$ENV" == "staging" ]
then
  eval $(aws s3 cp s3://example-bucket/stage-env.sh - | sed 's/^/export /')
else
  eval $(aws s3 cp s3://example-bucket/development-env.sh - | sed 's/^/export /')
fi

react-native start

在你的应用中,你可能会有一个配置文件,它有:

const FIRSTENV = process.env['FIRSTENV']
const SECONDENV = process.env['SECONDENV']

它将被巴别塔所取代:

const FIRSTENV = 'FIRSTVALUE'
const SECONDENV = 'SECONDVALUE'

记住你必须使用过程。env['STRING'] NOT process.env.STRING否则将不能正确转换。

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