1. 程式人生 > >利用CodePush對react-native專案熱更新(以android為例)

利用CodePush對react-native專案熱更新(以android為例)

CodePush是提供給React native 或 Cordova開發的一箇中央倉庫,開發者可以將js、image等程式碼資源上傳上去,客戶端啟動的時候根據版本拉去CodePush上的程式碼進行覆蓋來實現客戶端的熱更新。 1,安裝CodePush npm install -g code-push-cli  
安裝成功顯示目錄:

2,註冊code_push賬號: code-push register   提示輸入key,並彈出網頁
在這裡我選擇關聯github賬戶

拿到key輸入並提示登入code_push成功

相關命令 code-push login 登陸      code-push logout 登出  (登出後會刪除本地儲存的session,再次登入會進網頁重新生成key) 列出登陸的token code-push access-key rm <accessKye> 刪除某個 key值 新增刪除App命令: code-push app add 新增一個app code-push app remove 在賬號中移除一個app code-push app rename 重新命名一個已存在的app code-push app list ls  列出賬號下面所有的app code-push app transfer 把app的所有權轉移到另外的賬戶 新增一個app code-push app add MyApp-Android


下面我們建立一個react-native專案並完成code-push配置 首先建立專案 react-native init TestPush 建立完成進入TestPush根目錄 然後安裝code-push外掛 npm install --save react-native-code-push

安裝rnpm 執行命令  npm i -g rnpm  然後再連結外掛 rnpm link react-native-code-push  這條命令將會自動幫我們在anroid檔案中新增好設定。 包括如下配置{  在app的build.gradle中會自動新增 applyfrom:"../../node_modules/react-native-code-push/android/codepush.gradle
”  compile project(':react-native-code-push’) 在app settings.gradle中會自動新增 include ':react-native-code-push' project(':react-native-code-push').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-code-push/android/app’) } 接著執行code-push deployment ls MyApp-Android -k 獲取密匙

開啟android中MainApplication檔案新增 CodePush配置 這裡如果沒用as編譯器,CodePush是沒有自動import的 需要手動import com.microsoft.codepush.react.CodePush; 

接著把android版本號改為1.0.0, code-push必須用三位數的版本號
到此為止,配置已經完成了. 下面我們利用code-push做熱更新. 首先在js中引入code-push 最簡單的方式是在根component中進行上述策略控制。
  1. 在 js中載入 CodePush模組:

    import codePush from 'react-native-code-push'

    2.在 componentDidMount中呼叫 sync方法,後臺請求更新

    codePush.sync()
接著我們執行android專案 react-native run-android   
手機上會顯示welcome
我們隨便修改一下

在專案目錄下建一個bundles資料夾  mkdir bundles  打包js檔案 react-native bundle --platform android --entry-file index.android.js --bundle-output ./bundles/index.android.bundle --dev true
用code-push釋出更新 code-push release MyApp-Android ./bundles/index.android.bundle 1.0.0 --description "初次更新" --mandatory true 之前我已經上傳過一份了所以上傳重複的會出錯。第一次上傳肯定ok的。 設定手機不通過本機伺服器或許js檔案.開啟dev-setting — debugging — 點開debug server host &port for device  隨便輸入一串字元,不讓它獲取本機js伺服器程式碼 然後手機會從code-push伺服器拉取更新,測試成功,更新結果如下:  後續我將自建code-push伺服器做熱更新。