React native 可视化拆包

1、来源

    前提是使用metro配置来拆包,可以在之前的博客先了解下:https://blog.csdn.net/tyro_smallnew/article/details/83088216

如果是简单的基础包中包含各种第三方组件、业务包只包含自己写的业务代码情况下的拆包,很简单地使用命令行就可完成拆包。但有些时候业务包也会包含了第三方组件,比如只有一个业务包中使用了第三方日历组件而其他业务包不包含,这样第三方日历组件放在基础包有点冗余,需要单独把日历打在某个业务包中。这个情况用metro命令行打包就有点费力了,因为涉及到了依赖管理。

2、打包思路

    拆包主要有两个注意点,一个是module id固定化,二是拆分,业务包依赖第三方module影响到的是拆分这一点。

之前业务包拆分配置如下:

function postProcessModulesFilter(module) {
    const projectRootPath = __dirname;
    if(module['path'].indexOf('__prelude__')>=0){
        return false;
    }
    if(module['path'].indexOf(pathSep+'node_modules'+pathSep)>0){
        if('js'+pathSep+'script'+pathSep+'virtual'==module['output'][0]['type']){
            return true;
        }
        return false;
    }
    return true;
}

这里简单暴力地吧preclude和node_modules目录下的文件全部过滤掉,只打自己写的代码。

如果要打入第三方module就需要修改过滤规则,新的配置如下:

const noFilterModules = [/*你不想过滤的第三方模块名*/];

function packageToBundle(path){
  for(let i=0;i 0) {
      return true;
    }
  }
  return false;
}

function postProcessModulesFilter(module) {//返回false则过滤不编译
  const projectRootPath = __dirname;
  if(module['path'].indexOf('__prelude__')>=0){
    return false;
  }
  if(module['path'].indexOf(pathSep+'node_modules'+pathSep)>0){
    if(packageToBundle(module['path'])){
      return true;
    }
    if('js'+pathSep+'script'+pathSep+'virtual'==module['output'][0]['type']){
      return true;
    }
    return false;
  }
  return true;
}

直接把自己要打到业务包的模块名写到noFilterModules 数组去,这样就能把需要依赖的第三方module打进去。然而事情并没那么简单,因为一个第三方module可能还依赖另外一个module,而且层级可能达到5~6层,比如react-navigation,就单单这个第三方模块就有几十个依赖,写成配置如下:

const noFilterModules = ['react-navigation','clamp','create-react-context',
'hoist-non-react-statics','path-to-regexp','query-string','react-lifecycles-compat',
'react-native-safe-area-view','react-native-screens','react-navigation-deprecated-tab-navigator',
'react-navigation-drawer','react-navigation-stack','react-navigation-tabs',
'decode-uri-component','strict-uri-encode','isarray','hoist-non-react-statics',
'react-native-tab-view','react-native-drawer-layout-polyfill','react-navigation-stack',
'gud'
];//这里全是react-navigation所依赖的库名称

因此非常需要一个工具来帮忙计算依赖树,大概的思路就是读取package-lock.json然后计算出一个module依赖的其他所有module,并过滤掉基础包依赖的所有module。

3、成果

  为此我选用了electron作为开发工具制作了一个跨平台的可视化拆包工具,页面如下:

具体实现大家可以访问开源项目 https://github.com/smallnew/react-native-multibundler

 

 

你可能感兴趣的:(android,react,naitve)