我们知道,在debug模式下,RN
app是从本地的packager server
加载js
代码的,加载的地址如下:
-
iOS: http://localhost:8081/index.bundle?platform=ios&dev=true&minify=false
-
Android: http://localhost:8081/index.bundle?platform=android&dev=true&minify=false
其中默认情况下,打包后的bundle文件,iOS端后缀为jsbundle
(main.jsbundle),Android 端为 bundle
(index.android.bundle),不过都可以更改的
Android
源码:ReactNativeHost.java。
方法:
- getJSMainModuleName
/**
Returns the name of the main module. Determines the URL used to
fetch the JS bundle from the packager server. It is only used when
dev support is enabled. This is the first file to be executed once the
{@link ReactInstanceManager} is created. e.g. "index.android"
*/
protected String getJSMainModuleName() {
return "index.android";
}
获取JS端模块的入口文件,旧版本的RN区分平台为index.android.js
和index.ios.js
;在MainApplication.java
中重写了这个方法:
@Override
protected String getJSMainModuleName() {
return "index";
}
@Override
public boolean getUseDeveloperSupport() {
//获取是否是debug模式
return BuildConfig.DEBUG;
}
这个方法只有在debug
模式下才会被调用,他决定了从 package server 获取 JS bundle 的 URL
,一旦ReactInstanceManager
创建成功,他是第一个被执行的方法
- getJSBundleFile
/**
Returns a custom path of the bundle file. This is used in cases the
bundle should be loaded from a custom path. By default it is loaded from
Android assets, from a path specified by {@link getBundleAssetName}.
e.g. "file://sdcard/myapp_cache/index.android.bundle"
*/
protected @Nullable String getJSBundleFile() {
return null;
}
这个方法获取release时的js bundle 的路径,默认情况下他会加载Android assets下的用getBundleAssetName
方法指定的路径的文件;如果你要自定义bundle
文件的路径,可以使用这个方法;这就是react-native-code-push
的原理:在MainApplication.java
中重写了这个方法:
protected String getJSBundleFile() {
//使用code push
return CodePush.getJSBundleFile();
}
- getBundleAssetName
/**
Returns the name of the bundle in assets. If this is null,
and no file path is specified for the bundle, the app will only
work with {@code getUseDeveloperSupport} enabled and will always
try to load the JS bundle from the packager server.
e.g. "index.android.bundle"
*/
protected @Nullable String getBundleAssetName() {
return "index.android.bundle";
}
这个方法返回assets
文件夹下的bundle
文件的名字,如果返回null,并且没有指定bundle的文件路径,app就只能在debug模式下正常工作,并且永远尝试从packager server 加载js bundle 了
iOS
AppDelegate.m
- (NSURL *)sourceURLForBridge:(RCTBridge *)bridge
{
#if DEBUG
return [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];
#else
return [[NSBundle mainBundle] URLForResource:@"main" withExtension:@"jsbundle"];
#endif
}
Android 在打包APK时,会自动打包最新的js代码,生成的bundle
路径在app/build/intermediates/assets/release/
网友评论