我正在使用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。

其他回答

嗨,如果你正面临这个问题,试试这个,这对我有用,以后谢谢我

在bable.js

 plugins: [
      [
        "module:react-native-dotenv",
        {
          moduleName: "react-native-dotenv",
        },
      ],
    ],

use

import { YOURAPIKEY } from "react-native-dotenv";


inseted  of

import { YOURAPIKEY } from "@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中内置的__DEV__ polyfill。只要您不是为生产构建react native,它就会自动设置为true。

例如:

//vars.js

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

export {url, publicKey}

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

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

我使用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否则将不能正确转换。