react-native-config在iOS设备无法加载环境变量的排查求助
React Native Config iOS端环境变量加载失败(返回undefined)解决指南
针对你遇到的Android端正常、iOS端无法读取环境变量返回undefined的问题,补充以下排查和配置步骤:
1. 检查Xcode Scheme的环境变量注入配置
- 打开Xcode,进入项目Scheme(
Product > Scheme > Edit Scheme) - 切换到Run阶段的Arguments标签页
- 在
Environment Variables区域,确认已添加REACT_NATIVE_CONFIG_FILE,值设置为你的环境文件名(如.env或.env.staging) - 务必勾选下方的
Pass build configuration variables to environment选项
2. 验证Podfile配置的完整性
确保Podfile包含react-native-config的专属配置,适配RN 0.69版本:
require_relative '../node_modules/react-native/scripts/react_native_pods' require_relative '../node_modules/@react-native-community/cli-platform-ios/native_modules' target 'YourAppName' do config = use_native_modules! use_react_native!( :path => config[:reactNativePath], :hermes_enabled => true # 与你的项目Hermes配置保持一致 ) pod 'react-native-config', :path => '../node_modules/react-native-config' post_install do |installer| react_native_post_install(installer) __apply_Xcode_12_5_M1_post_install_workaround(installer) # 关键配置:禁用react-native-config的Info.plist自动生成 installer.pods_project.targets.each do |target| if target.name == 'react-native-config' target.build_configurations.each do |config| config.build_settings['GENERATE_INFOPLIST_FILE'] = 'NO' end end end end end
修改后执行以下命令:
cd ios && pod deintegrate && pod install && cd ..
3. 手动验证原生层是否能读取环境变量
排除RN层的问题,直接在iOS原生代码中测试:
- 打开
AppDelegate.m(Swift项目则打开AppDelegate.swift) - 添加日志代码:
// Objective-C NSString *myVar = [[NSProcessInfo processInfo] environment][@"MY_VARIABLE"]; NSLog(@"原生层读取MY_VARIABLE: %@", myVar);- 如果原生层也读取不到,说明环境变量未被正确注入,回到Scheme配置检查
- 如果原生层能读取到,说明RN层库集成异常,尝试重新安装react-native-config
4. 适配Xcode 15.1与iOS 18.0的兼容性
你使用的是较新的Xcode和iOS版本,react-native-config 1.5.x可能存在兼容问题:
- 升级react-native-config到最新稳定版(如2.x系列),参考官方文档调整配置
- 确认Xcode项目的
DEVELOPMENT_TEAM已正确设置,iOS 16+对签名和权限的要求更严格
5. 彻底清理缓存后重建
执行以下命令清理所有相关缓存:
# 重置RN缓存 npx react-native start --reset-cache # 清理Xcode派生数据和构建文件 rm -rf ~/Library/Developer/Xcode/DerivedData rm -rf ios/build # 重新安装依赖 npm install cd ios && pod install && cd ..
完成后通过Xcode重新构建并运行项目。
内容的提问来源于stack exchange,提问作者Anil Patel
相关产品推荐
相关产品推荐

