我正在使用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: '',
当前回答
如果你正在使用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”。我希望这对你有用。要了解更多信息,请阅读本文。
其他回答
如果你使用的是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
这创建了一个单例环境,可以从应用范围内的任何地方访问。你必须显式地要求(…)使用环境变量的任何组件的模块,但这是一件好事。
与其硬编码你的应用常量并在环境上进行切换(我将在稍后解释如何做到这一点),我建议使用12因素建议,让你的构建过程定义你的BASE_URL和API_KEY。
要回答如何将您的环境暴露为react-native,我建议使用Babel的Babel -plug -transform-inline-environment-variables。
为了让它工作,你需要下载这个插件,然后你需要设置一个.babelrc,它应该看起来像这样:
{
"presets": ["react-native"],
"plugins": [
"transform-inline-environment-variables"
]
}
因此,如果你通过运行API_KEY=my-app-id react-native bundle(或start, run-ios,或run-android)来编译你的react-native代码,那么你所要做的就是让你的代码看起来像这样:
const apiKey = process.env['API_KEY'];
然后巴别塔会用:
const apiKey = 'my-app-id';
我使用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文件时遇到了一些问题。
经过长时间的努力,我意识到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。