如何将Release Build指向本地主机JS Bundle?
实现Release Build指向本地JS Bundle的方案
要让CI构建的特殊Release版本加载本地主机的JS Bundle,需针对iOS和Android分别调整应用的JS加载逻辑,同时在CI流程中注入开关参数,具体步骤如下:
iOS 端实现
CI构建时添加编译宏
在Xcode的Release构建配置中,添加预编译宏ENABLE_LOCAL_JS_BUNDLE=1。CI可通过修改xcconfig文件或直接设置Xcode Build参数实现,确保特殊版本启用该宏。修改JS Bundle加载逻辑
打开AppDelegate.m(或AppDelegate.swift),调整JS代码入口的加载逻辑,优先使用本地Metro服务器的URL:NSURL *jsCodeLocation; #ifdef ENABLE_LOCAL_JS_BUNDLE // 指向本地Metro服务器,dev=true开启开发模式热重载 jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false"]; #else // 默认加载内置的Release JS Bundle jsCodeLocation = [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"]; #endif配置网络访问权限
在Info.plist中添加ATS例外,允许应用访问本地HTTP服务器:<key>NSAppTransportSecurity</key> <dict> <key>NSAllowsLocalNetworking</key> <true/> <key>NSExceptionDomains</key> <dict> <key>localhost</key> <dict> <key>NSExceptionAllowsInsecureHTTPLoads</key> <true/> </dict> </dict> </dict>
Android 端实现
CI构建时注入Gradle参数
在app模块的build.gradle中,为Release构建类型添加开关字段,CI可通过传递-PenableLocalJsBundle=true参数控制:buildTypes { release { // 原有Release配置... buildConfigField "boolean", "ENABLE_LOCAL_JS_BUNDLE", "${project.hasProperty('enableLocalJsBundle') ? enableLocalJsBundle : 'false'}" } }修改React Native Host配置
打开MainApplication.java,重写ReactNativeHost的相关方法,根据开关切换JS加载源:@Override protected ReactNativeHost createReactNativeHost() { return new ReactNativeHost(this) { @Override protected boolean getUseDeveloperSupport() { // 仅在启用本地JS时开启开发者支持,方便调试 return BuildConfig.ENABLE_LOCAL_JS_BUNDLE; } @Override protected String getJSMainModuleName() { return "index"; } @Override protected URL getJSBundleFile() { if (BuildConfig.ENABLE_LOCAL_JS_BUNDLE) { try { // 模拟器用10.0.2.2映射电脑localhost,真机替换为电脑局域网IP return new URL("http://10.0.2.2:8081/index.bundle?platform=android&dev=true&minify=false"); } catch (MalformedURLException e) { e.printStackTrace(); return super.getJSBundleFile(); } } else { return super.getJSBundleFile(); } } }; }确保网络权限
检查AndroidManifest.xml中是否包含网络权限,若没有则添加:<uses-permission android:name="android.permission.INTERNET" />
通用操作步骤
- 本地启动Metro服务器:用户在本地项目目录执行
npx react-native start,确保服务器正常运行。 - 设备与电脑连通:真机需和电脑在同一局域网,模拟器直接通过映射IP访问即可。
- 热重载生效:修改本地JS代码后,刷新应用即可看到更新效果,无需重新构建原生包。
内容的提问来源于stack exchange,提问作者Etai
相关产品推荐
相关产品推荐

