在不使用 EAS 的情况下使用环境变量
了解在 Expo 和 React Native 项目中管理环境变量的非 EAS 方法。
使用 EAS 环境变量 是管理云端构建和更新环境变量的推荐方式,但你仍然可以在本地或使用其他工具进行操作。
🌐 Using EAS Environment Variables is the recommended way to manage environment variables for cloud builds and updates, but you can still work locally or with other tooling.
在没有 EAS 的情况下管理环境变量
🌐 Managing environment variables without EAS
如果你想在不使用 EAS 的情况下管理环境变量,可以使用像 dotenv(基于 Node 的加载器)这样的工具,或像 Doppler 这样的服务来注入环境变量。这些工具允许你创建一个 .env 文件,用于存储你的环境变量。
🌐 If you want to manage environment variables without EAS, you can use tools like dotenv (Node-based loaders) or services such as Doppler that inject environment variables. These utilities allow you to create a .env file in which you can store your environment variables.
注意: 如果你在不使用 EAS 的情况下管理环境变量,请避免将秘密信息提交到 .env 文件中。
环境变量是如何加载的
🌐 How environment variables are loaded
在创建 .env 文件后,你需要确保该文件没有被列在你的 .gitignore 或 .easignore 文件中。然后,它就可以被 EAS 命令(如 eas build、eas update 等)识别。
🌐 After creating the .env file, you need to ensure that the file is not listed inside your .gitignore or .easignore files. Then it can be picked by EAS commands like eas build, eas update, and so on.
.env 文件会根据 标准 .env 文件 的规则加载,然后将你代码中所有对 process.env.EXPO_PUBLIC_[VARIABLE_NAME] 的引用替换为 .env 文件中对应的值。出于安全考虑,node_modules 目录下的代码不会受到影响。
🌐 The .env files load according to the standard .env file resolution and then replaces all references in your code to process.env.EXPO_PUBLIC_[VARIABLE_NAME] with the corresponding value set in the .**env **files. Code inside node_modules directory is not affected for security purposes.
欲了解更多信息,请参阅如何在 Expo CLI 中从 .env 文件读取环境变量。
在 EAS 托管中使用 .env 文件
🌐 Using .env files with EAS Hosting
在使用 EAS Hosting 的 .env 文件时,以 EXPO_PUBLIC_ 为前缀的环境变量在客户端代码和服务器端代码中都可用。未以 EXPO_PUBLIC_ 为前缀的变量仅在服务器端代码中可用。
🌐 When using .env files with EAS Hosting, environment variables prefixed with EXPO_PUBLIC_ are all available in the client-side code and the server-side code. The variables not prefixed with EXPO_PUBLIC_ are only available in the server-side code.
包括客户端和服务器端环境变量的步骤与使用 EAS 环境变量时相同。因此,在运行 npx export 命令之前,你需要确保本地 .env 文件中包含正确的环境变量。
🌐 The steps for including client-side and server-side environment variables are the same as when using EAS environment variables. So you need to ensure that your local .env files include the correct environment variables before running the npx export command.