codepush熱更新包減小體積-圖片資源優(yōu)化

場(chǎng)景

codepush更新包需要上傳bundle+assets,當(dāng)需要上傳資源包體積比較大的情況下,會(huì)消耗大量用戶流量且有下載失敗風(fēng)險(xiǎn),如出現(xiàn)緊急情況熱更新下發(fā)率低下會(huì)造成極大的影響;那么如何減少更新包體積呢?

改造方案

  • 如使用拆包方案,大部分情況下只上傳業(yè)務(wù)bundle,體積大概在50k以下,拆包方案參考RN拆包解決方案(一) bundle拆分
  • assets資源優(yōu)化,出現(xiàn)大量素材資源的情況下需要優(yōu)化處理,本次著重講解圖片資源加載優(yōu)化

codepush增量更新圖片資源

codepush已經(jīng)對(duì)圖片資源進(jìn)行增量?jī)?yōu)化,我們來(lái)看下它的實(shí)現(xiàn)流程:

  • 示例1:當(dāng)前版本1.0.0(1.png、2.png)-應(yīng)用程序沙盒,熱更新后包1.1.0(1.png、2.png)-文檔沙盒,codepush需全量下載1.1.0包中的圖片
  • 示例2:當(dāng)前版本熱更新后為1.1.0(1.png、2.png)-文檔沙盒,熱更新后包1.2.0(1.png、2.png、3.png)-文檔沙盒,如果前后版本(1.png、2.png)md5一致,codepush只會(huì)增量下載3.png,將1.1.0中的(1.png、2.png)圖片拷貝到1.2.0所在文檔沙盒目錄中

由此可見(jiàn),首次熱更新仍然需要全量下載消耗大量用戶流量,還有更好的方案嗎?

assets加載優(yōu)化

我們可以修改RN圖片加載流程,通過(guò)文檔沙盒目錄和本地應(yīng)用程序目錄結(jié)合,在更新后,判斷當(dāng)前bundle所在文檔沙盒路徑下是否存在資源,如果存在直接加載;如果沒(méi)有,就從本地應(yīng)用程序沙盒路徑中加載代替,如果能這樣處理,在沒(méi)有變更圖片資源的情況下,codepush只需要上傳bundle文件,資源圖片不需要一塊打包;若要想修改RN圖片加載流程,首先需要了解require圖片原理

require引入圖片原理

require方式返回的是一個(gè)整型, 對(duì)應(yīng)一個(gè)define函數(shù), 在bundle中體現(xiàn)為

//引用的地方  require方式
_react2.default.createElement(_reactNative.Image, { source: require(305                                      ), __source: { // 305 = ./Images/diary_mood_icon_alcohol_32.png
            fileName: _jsxFileName,
            lineNumber: 30
          }
        }),
 // uri 方式
_react2.default.createElement(_reactNative.Image, { source: { uir: 'https://www.baidu.com/img/bd_logo1.png', width: 100, height: 100 }, __source: {
            fileName: _jsxFileName,
            lineNumber: 31
          }
        })
//define地方
__d(/* RN472/Images/diary_mood_icon_alcohol_32.png */function(global, require, module, exports) {module.exports=require(161                                         ).registerAsset({"__packager_asset":true,"httpServerLocation":"/assets/Images","width":16,"height":16,"scales":[2,3],"hash":"7824b2f2a263b0bb181ff482a88fb813","name":"diary_mood_icon_alcohol_32","type":"png"}); // 161 = react-native/Libraries/Image/AssetRegistry
}, 305, null, "RN472/Images/diary_mood_icon_alcohol_32.png");

我們看到打包的時(shí)候,require圖片會(huì)轉(zhuǎn)換成如下格式的對(duì)象保存:

{
    "__packager_asset":true,  //是否是asset目錄下的資源
    "httpServerLocation":"/assets/Images", //server目錄地址
    "width":16, 
    "height":16,
    "scales":[2,3], //圖片scales   
    "hash":"7824b2f2a263b0bb181ff482a88fb813", //文件hash值
    "name":"diary_mood_icon_alcohol_32", //文件名
    "type":"png" //文件類型
}

我們看到引用的地方require(305)其實(shí)是執(zhí)行了require(161)的registerAsset的方法。查看161的define

__d(/* AssetRegistry */function(global, require, module, exports) {
'use strict';

var assets = [];

function registerAsset(asset) {
  return assets.push(asset);
}

function getAssetByID(assetId) {
  return assets[assetId - 1];
}

module.exports = { registerAsset: registerAsset, getAssetByID: getAssetByID };
}, 161, null, "AssetRegistry");

161對(duì)應(yīng)的就是AssetRegistry, AssetRegistry.registerAsset把圖片信息保存在成員數(shù)組assets中
查看Image.ios.js的render函數(shù)

  render: function() {
     const source = resolveAssetSource(this.props.source) || { uri: undefined, width: undefined, height: undefined };
    ...
    return (
      <RCTImageView
        {...this.props}
        style={style}
        resizeMode={resizeMode}
        tintColor={tintColor}
        source={sources}
      />
    );

通過(guò)resolveAssetSource函數(shù)

function resolveAssetSource(source: any): ?ResolvedAssetSource {
  if (typeof source === 'object') {
    return source;
  }

  var asset = AssetRegistry.getAssetByID(source);
  if (!asset) {
    return null;
  }

  const resolver = new AssetSourceResolver(getDevServerURL(), getBundleSourcePath(), asset);
  if (_customSourceTransformer) {
    return _customSourceTransformer(resolver);
  }
  
  return resolver.defaultAsset();

調(diào)用AssetRegistry.getAssetByID方法取出對(duì)應(yīng)的信息,傳遞到原生。

//傳遞到原生的source信息格式
{
    "__packager_asset" = 1;
    height = 16;
    scale = 2;
    uri = "http://Users/xxx/Library/Developer/CoreSimulator/Devices/2A0C4BE4-807B-4000-83EB-342B720A14DE/data/Containers/Bundle/Application/F84F1359-CBCD-4184-B3FD-2C7833B83A60/RN472.app/react-app/assets/Images/diary_mood_icon_alcohol_32@2x.png";
    width = 16;
}

iOS原生通過(guò)解析uri信息,獲取對(duì)應(yīng)的圖片

//RCTImageView.m
- (void)setImageSources:(NSArray<RCTImageSource *> *)imageSources
{
  if (![imageSources isEqual:_imageSources]) {
    _imageSources = [imageSources copy];
    _needsReload = YES;
  }
}

原理摘自鏈接
由此可見(jiàn),原生解析完uri就保存了圖片信息,我們可以在setImageSources的地方更改圖片信息后重新保存

創(chuàng)建RCTImageView分類

創(chuàng)建RCTImageView分類對(duì)setImageSources方法進(jìn)行hook,檢查圖片資源是否在目標(biāo)文檔沙盒目錄中,如未找到,選擇本地同名資源文件替換

@implementation RCTImageView (Bundle)

+ (void)load {
  static dispatch_once_t onceToken;
  dispatch_once(&onceToken, ^{
      [self swizzleMethod:@selector(bundle_setImageSources:) withMethod:@selector(setImageSources:)];
  });
}

//檢查資源文件是否在沙盒目錄中,如未找到,選擇本地同名資源文件替換
- (void)bundle_setImageSources:(NSArray<RCTImageSource *> *)imageSources
{
    NSMutableArray<RCTImageSource *> *newImagesources = [[NSMutableArray<RCTImageSource *> alloc]init];
    for (RCTImageSource *imageSource in imageSources) {
        NSString *imageUrl = imageSource.request.URL.absoluteString;
        if ([imageUrl hasPrefix:@"http"] || [imageUrl hasPrefix:@"data:image/"]) {//網(wǎng)絡(luò)素材和base646圖片不予處理
            [newImagesources addObject:imageSource];
            continue;
        }
        if ([imageUrl hasPrefix:@"file://"]) {
            imageUrl = [imageUrl substringFromIndex:7];
        }
        imageUrl = [imageUrl stringByURLDecoded];
        if ([[NSFileManager defaultManager] fileExistsAtPath:imageUrl]) {//文件存在直接使用
            [newImagesources addObject:imageSource];
            continue;
        }
        NSRange range = [imageUrl rangeOfString:@"assets/"];
        if (range.length > 0 && range.location > 0) {//若文件不存在,檢查是否在應(yīng)用程序沙盒中存在同名文件
            NSString *releateBundlePath = [imageUrl substringFromIndex:range.location];
            NSString *mainPath = [[NSBundle mainBundle] bundlePath];
            //將文檔沙盒路徑替換成應(yīng)用程序沙盒路徑獲取圖片
            NSString *localImageUrl = [mainPath stringByAppendingPathComponent:releateBundlePath];
            //轉(zhuǎn)換成RCTImageSource
            RCTImageSource *newImageSource = [RCTConvert RCTImageSource:@{
                                                                          @"__packager_asset":@1,
                                                                          @"height":@(imageSource.size.height),
                                                                          @"width":@(imageSource.size.width),
                                                                          @"scale":@(imageSource.scale),
                                                                          @"uri":localImageUrl
                                                                          }];
            [newImagesources addObject:newImageSource];
        }
    }
    [self bundle_setImageSources:newImagesources];
}

此方案雖然可行,但是需要對(duì)原生代碼進(jìn)行hook,且Android端也同樣需要實(shí)現(xiàn),對(duì)原生不熟悉的同學(xué)不大友好,還有別的方案嗎?

最終方案

使用hook的方式對(duì)react-native js進(jìn)行修改,保證了項(xiàng)目與node_modules耦合度降低
實(shí)現(xiàn)方式:
(1)通過(guò) hook 的方式重新定義 defaultAsset() 方法。
(2)檢查圖片資源是否在目標(biāo)文檔沙盒目錄中,如未找到,選擇本地同名資源文件替換。
核心代碼如下:

import { NativeModules } from 'react-native';    
import AssetSourceResolver from "react-native/Libraries/Image/AssetSourceResolver";
import _ from 'lodash';
 
let iOSRelateMainBundlePath = '';
let _sourceCodeScriptURL = '';
 
// ios 平臺(tái)下獲取 jsbundle 默認(rèn)路徑
const defaultMainBundePath = AssetsLoad.DefaultMainBundlePath;
 
function getSourceCodeScriptURL() {
    if (_sourceCodeScriptURL) {
        return _sourceCodeScriptURL;
    }
    // 調(diào)用Native module獲取 JSbundle 路徑
    // RN允許開(kāi)發(fā)者在Native端自定義JS的加載路徑,在JS端可以調(diào)用SourceCode.scriptURL來(lái)獲取 
    // 如果開(kāi)發(fā)者未指定JSbundle的路徑,則在離線環(huán)境下返回asset目錄
    let sourceCode =
        global.nativeExtensions && global.nativeExtensions.SourceCode;
    if (!sourceCode) {
        sourceCode = NativeModules && NativeModules.SourceCode;
    }
    _sourceCodeScriptURL = sourceCode.scriptURL;
    return _sourceCodeScriptURL;
}
 
// 獲取bundle目錄下所有drawable 圖片資源路徑
let drawablePathInfos = [];
AssetsLoad.searchDrawableFile(getSourceCodeScriptURL(),
     (retArray)=>{
      drawablePathInfos = drawablePathInfos.concat(retArray);
});
// hook defaultAsset方法,自定義圖片加載方式
AssetSourceResolver.prototype.defaultAsset = _.wrap(AssetSourceResolver.prototype.defaultAsset, function (func, ...args) {
     if (this.isLoadedFromServer()) {
         return this.assetServerURL();
     }
     if (Platform.OS === 'android') {
         if(this.isLoadedFromFileSystem()) {
             // 獲取圖片資源路徑
             let resolvedAssetSource = this.drawableFolderInBundle();
             let resPath = resolvedAssetSource.uri;
             // 獲取JSBundle文件所在目錄下的所有drawable文件路徑,并判斷當(dāng)前圖片路徑是否存在
             // 如果存在,直接返回
             if(drawablePathInfos.includes(resPath)) {
                 return resolvedAssetSource;
             }
             // 判斷圖片資源是否存在本地文件目錄
             let isFileExist = AssetsLoad.isFileExist(resPath);
             // 存在直接返回
             if(isFileExist) {
                 return resolvedAssetSource;
             } else {
                 // 不存在,則根據(jù)資源 Id 從apk包下的drawable目錄加載
                 return this.resourceIdentifierWithoutScale();
             }
         } else {
             // 則根據(jù)資源 Id 從apk包下的drawable目錄加載
             return this.resourceIdentifierWithoutScale();
         }
 
     } else {
         let iOSAsset = this.scaledAssetURLNearBundle();
         let isFileExist =  AssetsLoad.isFileExist(iOSAsset.uri);
         isFileExist = false;
         if(isFileExist) {
             return iOSAsset;
         } else {
             let oriJsBundleUrl = 'file://'+ defaultMainBundePath +'/' + iOSRelateMainBundlePath;
             iOSAsset.uri = iOSAsset.uri.replace(this.jsbundleUrl, oriJsBundleUrl);
             return iOSAsset;
         }
     }
});

該方案參考鏈接

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容