玩玩RN--1 RCTBundleURLProvider

前言

    现在团队在全面转weex,我自然不能抽身事外,去年来公司到今年的1月份,算算玩RN也完了快五个月,下面可能一段时间都会花精力在weex上,所以现在写下这个笔记,省的以后一点印象都没有,徒增笑柄。

接触rn

    第一次接触到rn这个词是在16年10月份,那还是我的上一家公司,当时还向领导推荐过,但是后来不了了之。然后来新的公司,刚好新公司有一个内部项目使用这个写的,所以就接了下来,这个之后,开始慢慢接触RN,了解RN.

rn的使用

关于rn的使用,我不想说很多,因为各种问题网上差不多都有详细的答案。

RN的启动

  NSURL *jsCodeLocation;

  jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];

  RCTRootView *rootView = [[RCTRootView alloc] initWithBundleURL:jsCodeLocation
                                                      moduleName:@"RNProject"
                                               initialProperties:nil
                                                   launchOptions:launchOptions];

这个是iOS中rn的启动代码,看代码我们知道通过bundle然后生成一个View。

  • 第一个语句
   jsCodeLocation = [[RCTBundleURLProvider sharedSettings] jsBundleURLForBundleRoot:@"index" fallbackResource:nil];

这个语句是我们用RN的脚手架生成一个app的时候官方调用的一个方法,而我们平时用rn都是在原生中有几个页面,用的方法可能是这两个

   jsCodeLocation = [NSURL URLWithString:[[NSBundle mainBundle]pathForResource:@"main" ofType:@"jsbundle"]];
   jsCodeLocation = [NSURL URLWithString:@"http://localhost:8081/index.bundle?platform=ios"];

上一次是加载本地文件 第二个是debug时用的,加载本地服务器用的。

现在我们来看看RN脚手架所用的URL是怎么去的。

    NSString *packagerServerHost = [self packagerServerHost];
  if (!packagerServerHost) {
    return [self jsBundleURLForFallbackResource:resourceName fallbackExtension:extension];
  } else {
    return [RCTBundleURLProvider jsBundleURLForBundleRoot:bundleRoot
                                             packagerHost:packagerServerHost
                                                enableDev:[self enableDev]
                                       enableMinification:[self enableMinification]];
  }
  • 首先获取packagerServerHost 这里会看是不是debug 当debug的时候会给一个guessPackagerHost 这个通过ip.txt来配置,不配置的话就是localhost
  • 如果packagerServerHost 为空的时候调用
[self jsBundleURLForFallbackResource:resourceName fallbackExtension:extension];

这个方法很简单 获取本地的js文件。

  • 如果packagerServerHost不为空 会调用
[RCTBundleURLProvider jsBundleURLForBundleRoot:bundleRoot
packagerHost:packagerServerHost enableDev:[self enableDev]                                   enableMinification:[self enableMinification]];

我们再来看这个方法,进去之后我们发现他的作用也是生成
http://localhost:8081/index.bundle?platform=ios 这样的一个字符串生成的URL。

综上,结论是RCTBundleURLProvider这个类负责是url的生成,他会根据你的环境和配置来生成本地或者远端的URL,但是如果我们本地的js文件的路径比较深,后者后缀不是bundle都需要注意匹配。

你可能感兴趣的:(玩玩RN--1 RCTBundleURLProvider)