美文网首页
2020-04-30 react native bundle原理

2020-04-30 react native bundle原理

作者: KingAmo | 来源:发表于2020-04-30 18:32 被阅读0次

我们知道,在debug模式下,RN app是从本地的packager server加载js代码的,加载的地址如下:

其中默认情况下,打包后的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.jsindex.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
}

https://stackoverflow.com/questions/40050253/change-entry-file-path-of-android-and-ios-in-react-native-project

Android 在打包APK时,会自动打包最新的js代码,生成的bundle路径在app/build/intermediates/assets/release/

image.png

相关文章

网友评论

      本文标题:2020-04-30 react native bundle原理

      本文链接:https://www.haomeiwen.com/subject/uumkyhtx.html