了解如何在 Expo 项目中使用环境变量。
环境变量是在源代码外部配置的键值对,允许你的应用根据环境的不同而表现不同。例如,你可以在构建应用的测试版本时启用或禁用某些功能,或者在构建生产时切换到不同的 API 端点。
¥Environment variables are key-value pairs configured outside your source code that allow your app to behave differently depending on the environment. For example, you can enable or disable certain features when building a test version of your app, or switch to a different API endpoint when building for production.
每当你使用 Expo CLI 时,例如在本地开发模式下运行 npx expo start
启动应用时,Expo CLI 都会自动从 .env 文件加载带有 EXPO_PUBLIC_
前缀的环境变量,以便在 JavaScript 代码中使用。
¥The Expo CLI will automatically load environment variables with an EXPO_PUBLIC_
prefix from .env files for use within your JavaScript code whenever you use the Expo CLI, such as when running npx expo start
to start your app in local development mode.
在 SDK 49 及更高版本中可用。
¥Available in SDK 49 and higher.
¥Reading environment variables from .env files
在项目目录的根目录中创建一个 .env 文件,并以 EXPO_PUBLIC_[NAME]=VALUE
的形式在新行中添加特定于环境的变量:
¥Create a .env file in the root of your project directory and add environment-specific variables on new lines in the form of EXPO_PUBLIC_[NAME]=VALUE
:
EXPO_PUBLIC_API_URL=https://staging.example.com
EXPO_PUBLIC_API_KEY=abc123
现在你可以直接在源代码中使用环境变量:
¥Now you can use environment variables directly in your source code:
import { Button } from 'react-native';
function Post() {
const apiUrl = process.env.EXPO_PUBLIC_API_URL;
async function onPress() {
await fetch(apiUrl, { ... })
}
return <Button onPress={onPress} title="Post" />;
}
当你运行 npx expo start
时,应用包中的 process.env.EXPO_PUBLIC_API_URL
将被替换为 https://staging.example.com
。你可以在编辑代码时更新变量,而无需重新启动 Expo CLI 或清除缓存。你将需要执行完全重新加载(例如,摇动手势,然后在 Expo Go 或你的开发版本中重新加载)才能查看更新的值。
¥When you run npx expo start
, process.env.EXPO_PUBLIC_API_URL
will be replaced with https://staging.example.com
in your app bundle. Variables can be updated as you edit your code without restarting the Expo CLI or clearing the cache. You will need to perform a full reload (for example, shake gesture and then Reload in Expo Go or your development build) to see the updated value.
不要在EXPO_PUBLIC_
变量中存储敏感信息,例如私钥。这些变量将以纯文本形式在编译的应用中可见。
¥How variables are loaded
Expo CLI 根据 标准 .env 文件解析 加载 .env 文件,然后将代码中对 process.env.EXPO_PUBLIC_[VARNAME]
的所有引用替换为 .env 文件中设置的相应值。出于安全目的,node_modules 内的代码不会受到影响。
¥Expo CLI loads .env files according to the standard .env file resolution and then replaces all references in your code to process.env.EXPO_PUBLIC_[VARNAME]
with the corresponding value set in the .env files. Code inside node_modules is not affected for security purposes.
¥How to read from environment variables
process.env
的属性,才能内联。例如,表达式 process.env.EXPO_PUBLIC_KEY
有效并且将被内联。¥ Every environment variable must be statically referenced as a property of
process.env
using JavaScript's dot notation for it to be inlined. For example, the expression
process.env.EXPO_PUBLIC_KEY
is valid and will be inlined.
process.env['EXPO_PUBLIC_KEY']
或 const {EXPO_PUBLIC_X} = process.env
无效,不会被内联。¥ Alternative versions of the expression are not supported. For example,
process.env['EXPO_PUBLIC_KEY']
or const {EXPO_PUBLIC_X} = process.env
is invalid and will not
be inlined.
¥Using multiple .env files to define separate environments
你可以定义任何 标准 .env 文件,因此可以有单独的 .env、.env.local、.env.Production 等文件,并且它们将根据标准优先级加载。
¥You can define any of the standard .env files, so it is possible to have separate .env, .env.local, .env.production and so on, files and they will load according to the standard priority.
你可以选择将默认的 .env 文件或其他标准配置提交到版本控制,但通常 .env.local 文件应添加到你的 .gitignore 中:
¥You may choose to commit the default .env file or other standard configurations to version control, but generally .env.local files should be added to your .gitignore:
.env*.local
如果你创建特定于环境的文件,例如 .env.test,则可以在运行 Expo CLI 时通过设置 NODE_ENV
来加载它:
¥If you create an environment-specific file, like .env.test, you can load it by setting NODE_ENV
when running the Expo CLI:
-
NODE_ENV=test npx expo start
¥Disabling environment variables
Expo CLI 中的环境变量有两部分,并且都可以禁用:
¥Environment variables in Expo CLI have two parts and both can be disabled:
Expo CLI 自动将 .env 文件加载到全局进程中。要禁用此行为,请在运行任何 Expo CLI 命令之前将环境变量 EXPO_NO_DOTENV
设置为 1
:EXPO_NO_DOTENV=1
。
¥Expo CLI automatically loads the .env files into the global process. To disable this behavior, set the environment variable EXPO_NO_DOTENV
to 1
before running any Expo CLI command: EXPO_NO_DOTENV=1
.
Expo 的 Metro 配置包括客户端 JavaScript 包中环境变量的内联序列化。要禁用此行为,你可以使用 EXPO_NO_CLIENT_ENV_VARS=1
。
¥Expo's Metro config includes the inline serialization of environment variables in the client JavaScript bundle. To disable this behavior, you can use EXPO_NO_CLIENT_ENV_VARS=1
.
如果你遇到环境变量问题,可以尝试禁用其中一项或两项功能。
¥If you're experiencing issues with environment variables, you can try disabling one or both of these features.
¥Environment variables in Expo Application Services
¥EAS Build
EAS 构建 使用 Metro Bundler 构建嵌入在应用二进制文件中的 JavaScript 包,因此它将使用随构建作业上传的 .env 文件将 EXPO_PUBLIC_
变量内联到你的代码中。EAS Build 还允许你在 eas.json 的构建配置文件中以及通过 EAS Secrets 定义环境变量。查看 环境变量和构建秘密 上的 EAS 构建文档以获取更多信息。
¥EAS Build uses Metro Bundler to build the JavaScript bundle embedded within your app binary, so it will use .env files uploaded with your build job to inline EXPO_PUBLIC_
variables into your code. EAS Build also lets you define environment variables within build profiles in eas.json and via EAS Secrets. Check out the EAS Build documentation on environment variables and build secrets for more information.
¥EAS Update
EAS 更新 在本地环境或 CI 中使用 Metro Bundler 来构建应用包,因此它将使用可用的 .env 文件将 EXPO_PUBLIC_
变量内联到你的代码中。查看 环境变量 上的 EAS 更新文档以了解更多信息。
¥EAS Update uses Metro Bundler in your local environment or CI to build your app bundle, so it will use available .env files to inline EXPO_PUBLIC_
variables into your code. Check out the EAS Update documentation on environment variables for more information.
¥Migrating to Expo environment variables
¥From react-native-config
更新你的 .env 文件,以在 JavaScript 代码中使用的任何变量添加 EXPO_PUBLIC_
前缀:
¥Update your .env files to prefix any variables used within your JavaScript code with EXPO_PUBLIC_
:
- API_URL=https://myapi.com
+ EXPO_PUBLIC_API_URL=https://myapi.com
如果你有任何非标准 .env 文件(例如 .env.staging),你将需要将它们迁移到 标准 .env 文件.1.1 或 .env.staging 之一。
¥If you have any non-standard .env files (for example, .env.staging), you will need to migrate those to one of the standard .env files.
然后更新你的代码以使用 process.env.EXPO_PUBLIC_[VARNAME]
:
¥Then update your code to use process.env.EXPO_PUBLIC_[VARNAME]
:
- import Config from "react-native-config";
- const apiUrl = Config.API_URL;
+ const apiUrl = process.env.EXPO_PUBLIC_API_URL;
¥From babel-plugin-transform-inline-environment-variables
使用 Babel 插件来转换代码中的环境变量引用与 Expo 环境变量的工作方式类似。在 .env 文件中设置变量并更新变量名称以使用 EXPO_PUBLIC_
前缀:
¥Using a Babel plugin to transform your environment variable references in your code is similar to how Expo environment variables work. Set your variables inside a .env file and update your variable names to use the EXPO_PUBLIC_
prefix:
- const apiUrl = process.env.API_URL;
+ const apiUrl = process.env.EXPO_PUBLIC_API_URL;
然后你可以从 Babel 配置中删除该插件:
¥Then you can remove the plugin from your Babel config:
module.exports = function (api) {
api.cache(true);
return {
presets: ['babel-preset-expo'],
-- plugins: ['transform-inline-environment-variables'],
};
};
更新 Babel 配置文件后,请务必使用 npx expo start -c
清除缓存。
¥After updating your Babel config file, be sure to clear your cache with npx expo start -c
.
¥From direnv
将 JavaScript 中使用的任何环境变量从其 .envrc 文件移动到 .env 文件,并在其前面加上 EXPO_PUBLIC_
前缀。
¥Move any environment variables used in your JavaScript from their .envrc file to a .env file and prefix it with EXPO_PUBLIC_
.
以前使用 direnv
时,你需要使用从 process.env
读取的 动态应用配置 在 extra
字段上设置环境变量,以便可以通过 expo-constants
在 JavaScript 代码中使用它们。将这些引用直接移到你的代码中,添加 EXPO_PUBLIC_
前缀:
¥Previously with direnv
, you would need to use a dynamic app config that reads from process.env
to set environment variables on the extra
field so they can be used in your JavaScript code via expo-constants
. Move those references directly into your code, adding the EXPO_PUBLIC_
prefix:
- import Constants from 'expo-constants';
- const apiUrl = Constants.expoConfig.extra.apiUrl;
+ const apiUrl = process.env.EXPO_PUBLIC_API_URL;
direnv
根据当前目录自动加载和卸载 shell 中的环境变量,这意味着它可以直接影响在其中运行的任何进程的环境,而不仅仅是 Expo CLI。你可能希望继续将direnv
用于 JavaScript 代码中未使用的其他环境变量。¥
direnv
automatically loads and unloads environment variables in your shell depending on your current directory, meaning it can affect the environment for any process running in that directly, not just the Expo CLI. You will likely want to continue usingdirenv
for other environment variables that are not used in your JavaScript code.
¥Security considerations
切勿将敏感密钥存储在前缀为 EXPO_PUBLIC_
的环境变量中。当终端用户运行你的应用时,他们可以访问你的应用中的所有代码和嵌入的环境变量。了解有关 存储敏感信息 的更多信息。
¥Never store sensitive secrets in environment variables that are prefixed with EXPO_PUBLIC_
. When an end-user runs your app, they have access to all of the code and embedded environment variables in your app. Read more about storing sensitive info.