我正在使用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: '',
当前回答
不要传递像VAR=value react-native run-android或VAR=value react-native run-ios这样的变量。这些变量只有当我们在开始命令中传递它们时才可以访问,即VAR=value react-native start——reset-cache。
你可以通过3个简单的步骤来实现这一点:-
通过运行npm i babel-plugin-transform-inline-environment-variables——save-dev安装babel-plugin-transform-inline-environment-variables。 在.bablerc或babel.config.js中添加"plugins": ["transform-inline-environment-variables"] 在启动metro bundle时传递变量,即VAR=value react-native start -reset-cache,不要在react-native run-android或react-native run-ios命令中传递这些变量。
请记住,使用——reset-cache标志是必需的,否则变量的变化将不会被应用。
其他回答
你也可以有不同的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;
对于最新的RN版本,您可以使用这个本机模块:https://github.com/luggit/react-native-config
如果你正在使用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”。我希望这对你有用。要了解更多信息,请阅读本文。
我使用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否则将不能正确转换。
经过长时间的努力,我意识到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。