我正在使用react-native来构建一个跨平台的应用程序,但我不知道如何设置环境变量,以便我可以有不同的常量为不同的环境。
例子:
development:
BASE_URL: '',
API_KEY: '',
staging:
BASE_URL: '',
API_KEY: '',
production:
BASE_URL: '',
API_KEY: '',
我正在使用react-native来构建一个跨平台的应用程序,但我不知道如何设置环境变量,以便我可以有不同的常量为不同的环境。
例子:
development:
BASE_URL: '',
API_KEY: '',
staging:
BASE_URL: '',
API_KEY: '',
production:
BASE_URL: '',
API_KEY: '',
当前回答
为了解决这个问题,我使用了react-native中内置的__DEV__ polyfill。只要您不是为生产构建react native,它就会自动设置为true。
例如:
//vars.js
let url, publicKey;
if (__DEV__) {
url = ...
publicKey = ...
} else {
url = ...
publicKey = ...
}
export {url, publicKey}
然后只需导入{url}从'../vars',你总是会得到正确的。不幸的是,如果你想要两个以上的环境,这就行不通了,但它很简单,而且不需要向你的项目添加更多的依赖项。
其他回答
用于设置环境变量的具体方法将因您使用的CI服务、构建方法、平台和工具而异。
如果你正在使用Buddybuild for CI来构建应用程序和管理环境变量,并且你需要从JS中访问配置,创建一个带有键(空字符串值)的env.js.example用于签入源代码控制,并在构建时在后克隆步骤中使用Buddybuild生成一个env.js文件,从构建日志中隐藏文件内容,如下所示:
#!/usr/bin/env bash
ENVJS_FILE="$BUDDYBUILD_WORKSPACE/env.js"
# Echo what's happening to the build logs
echo Creating environment config file
# Create `env.js` file in project root
touch $ENVJS_FILE
# Write environment config to file, hiding from build logs
tee $ENVJS_FILE > /dev/null <<EOF
module.exports = {
AUTH0_CLIENT_ID: '$AUTH0_CLIENT_ID',
AUTH0_DOMAIN: '$AUTH0_DOMAIN'
}
EOF
提示:不要忘记将env.js添加到.gitignore中,这样在开发过程中配置和秘密就不会意外地检入源代码控制。
然后,您可以使用Buddybuild变量(例如buddybuild_variables)管理文件的编写方式,以更好地控制在构建时如何生成配置。
我使用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文件时遇到了一些问题。
你也可以有不同的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;
如果你使用的是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并没有正式提供这个功能。这是在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。