RN利用codepush實(shí)現(xiàn)熱更新(更新中..)

如果你對codepush實(shí)現(xiàn)的熱更新還不了解,當(dāng)你看到這篇文章,恭喜你賺大了.
不扯沒用的,現(xiàn)在步入正題說說熱更新那些事!

一.安裝 CodePush CLI

//目的:  安裝完這個(gè)就可以直接使用code-push命令
//注意:這個(gè)CodePush指令只需要全局安裝一次即可,如果第一次安裝成功了,那后面就不在需要安裝
$ npm install -g code-push-cli

二.注冊并登錄 CodePush賬號

  • 微軟服務(wù)器
//注冊CodePush賬號也很簡單,同樣是只需簡單的執(zhí)行下面的命令,同樣這個(gè)注冊操作也是全局只需要注冊一次即可
code-push register

這里會跳進(jìn)瀏覽器,可以使用github或者M(jìn)icrosoft帳戶注冊,注冊成功后將會自動登錄,生成相應(yīng)的access token,按照提示在終端輸入剛生成的access token,成功則登錄.

  • 自建服務(wù)器
//登錄
$ code-push login http://服務(wù)器IP:3000/
//需要輸入默認(rèn)賬號密碼為 account:  admin password:  123456
屏幕快照 2018-09-14 下午8.26.41.png

修改默認(rèn)密碼:

$ curl -X PATCH -H "Authorization: Bearer 登錄獲取的token" -H "Accept: application/json" -H "Content-Type:application/json" -d '{"oldPassword":"123456","newPassword":"654321"}' http://服務(wù)器IP:3000/users/password

CodePush注冊登錄相關(guān)命令:

code-push login 登陸
code-push logout 注銷
code-push access-key ls 列出登陸的token
code-push access-key rm <accessKye> 刪除某個(gè) access-key

三.在CodePush服務(wù)器注冊App

//添加iOS平臺應(yīng)用
$ code-push app add productName-ios ios react-native
//添加Android平臺應(yīng)用
$ code-push app add productName-android android react-native

我們可以輸入如下命令來查看我們剛剛添加的App

$ code-push app list

CodePush管理App的相關(guān)命令:

code-push app add 在賬號里面添加一個(gè)新的app
code-push app remove 或者 rm 在賬號里移除一個(gè)app
code-push app rename 重命名一個(gè)存在app
code-push app list 或則 ls 列出賬號下面的所有app
code-push app transfer 把a(bǔ)pp的所有權(quán)轉(zhuǎn)移到另外一個(gè)賬號

四.集成code-push到reactNative中

安裝組件

//在項(xiàng)目根目錄
$ yarn add react-native-code-push

在node_modules中如果出現(xiàn)


0383CE8B-1A59-40C2-A11D-803B542250E7.png

恭喜你安裝react-native-code-push成功了

我們在RN項(xiàng)目的根組件中添加熱更新邏輯代碼如下

import React, { Component } from 'react';
import {
  AppRegistry,
  Dimensions,
  Image,
  StyleSheet,
  Text,
  TouchableOpacity,
  View,
} from 'react-native';

import CodePush from "react-native-code-push";

class App extends Component<{}> {
  constructor() {
    super();
    this.state = { restartAllowed: true };
  }

  codePushStatusDidChange(syncStatus) {
    switch(syncStatus) {
      case CodePush.SyncStatus.CHECKING_FOR_UPDATE:
        this.setState({ syncMessage: "Checking for update." });
        break;
      case CodePush.SyncStatus.DOWNLOADING_PACKAGE:
        this.setState({ syncMessage: "Downloading package." });
        break;
      case CodePush.SyncStatus.AWAITING_USER_ACTION:
        this.setState({ syncMessage: "Awaiting user action." });
        break;
      case CodePush.SyncStatus.INSTALLING_UPDATE:
        this.setState({ syncMessage: "Installing update." });
        break;
      case CodePush.SyncStatus.UP_TO_DATE:
        this.setState({ syncMessage: "App up to date.", progress: false });
        break;
      case CodePush.SyncStatus.UPDATE_IGNORED:
        this.setState({ syncMessage: "Update cancelled by user.", progress: false });
        break;
      case CodePush.SyncStatus.UPDATE_INSTALLED:
        this.setState({ syncMessage: "Update installed and will be applied on restart.", progress: false });
        break;
      case CodePush.SyncStatus.UNKNOWN_ERROR:
        this.setState({ syncMessage: "An unknown error occurred.", progress: false });
        break;
    }
  }

  codePushDownloadDidProgress(progress) {
    this.setState({ progress });
  }

  toggleAllowRestart() {
    this.state.restartAllowed
      ? CodePush.disallowRestart()
      : CodePush.allowRestart();

    this.setState({ restartAllowed: !this.state.restartAllowed });
  }

  getUpdateMetadata() {
    CodePush.getUpdateMetadata(CodePush.UpdateState.RUNNING)
      .then((metadata: LocalPackage) => {
        this.setState({ syncMessage: metadata ? JSON.stringify(metadata) : "Running binary version", progress: false });
      }, (error: any) => {
        this.setState({ syncMessage: "Error: " + error, progress: false });
      });
  }

  /** Update is downloaded silently, and applied on restart (recommended) */
  sync() {
    CodePush.disallowRestart();
    CodePush.sync(
      {},
      this.codePushStatusDidChange.bind(this),
      this.codePushDownloadDidProgress.bind(this)
    );
  }

  /** Update pops a confirmation dialog, and then immediately reboots the app */
  syncImmediate() {
    CodePush.sync(
      { installMode: CodePush.InstallMode.IMMEDIATE, updateDialog: true },
      this.codePushStatusDidChange.bind(this),
      this.codePushDownloadDidProgress.bind(this)
    );
  }

  render() {
    let progressView;

    if (this.state.progress) {
      progressView = (
        <Text style={styles.messages}>{this.state.progress.receivedBytes} of {this.state.progress.totalBytes} bytes received</Text>
      );
    }

    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to CodePush!
        </Text>
        <TouchableOpacity onPress={this.sync.bind(this)}>
          <Text style={styles.syncButton}>Press for background sync</Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={this.syncImmediate.bind(this)}>
          <Text style={styles.syncButton}>Press for dialog-driven sync</Text>
        </TouchableOpacity>
        {progressView}
        <Image style={styles.image} resizeMode={Image.resizeMode.contain} source={require("./images/laptop_phone_howitworks.png")}/>
        {/*<TouchableOpacity onPress={this.toggleAllowRestart.bind(this)}>*/}
          {/*<Text style={styles.restartToggleButton}>Restart { this.state.restartAllowed ? "allowed" : "forbidden"}</Text>*/}
        {/*</TouchableOpacity>*/}
        <TouchableOpacity onPress={this.getUpdateMetadata.bind(this)}>
          <Text style={styles.syncButton}>Press for Update Metadata</Text>
        </TouchableOpacity>
        <Text style={styles.messages}>{this.state.syncMessage || ""}</Text>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    alignItems: "center",
    backgroundColor: "white",
    paddingTop: 50
  },
  image: {
    margin: 30,
    width: Dimensions.get("window").width - 100,
    height: 365 * (Dimensions.get("window").width - 100) / 651,
  },
  messages: {
    marginTop: 30,
    textAlign: "center",
  },
  restartToggleButton: {
    color: "blue",
    fontSize: 17
  },
  syncButton: {
    color: "green",
    fontSize: 17
  },
  welcome: {
    fontSize: 20,
    textAlign: "center",
    margin: 20
  },
});

/**
 * Configured with a MANUAL check frequency for easy testing. For production apps, it is recommended to configure a
 * different check frequency, such as ON_APP_START, for a 'hands-off' approach where CodePush.sync() does not
 * need to be explicitly called. All options of CodePush.sync() are also available in this decorator.
 */
let codePushOptions = { checkFrequency: CodePush.CheckFrequency.MANUAL };

App = CodePush(codePushOptions)(App);

export default App;

五.原生應(yīng)用中配置CodePush

這里原生應(yīng)用中配置CodePush我們需要分別配置iOS平臺和Android平臺

iOS平臺

一般有三種方法:RNPM、CocoaPods 、"Manual"詳細(xì)可參考CodePush的Github:https://github.com/Microsoft/react-native-code-push
我著用的是RNPM,如果你項(xiàng)目使用CocoaPods集成的,那推薦使用cocoaPods:
1.安裝rnpm

$ npm i -g rnpm

2.查看下之前在code-push創(chuàng)建的app,下面會用到

$ code-push deployment ls <appName> -k

查看結(jié)果如


FC554C37-B4BF-4137-9E27-8C7A69C59D12.png

3.將code-push集成到xcode

$ react-native link react-native-code-push

這里需要輸入Deployment Key (上面查看的那個(gè)),填寫Staging對應(yīng)的Key就行,這個(gè)是測試環(huán)境的,安卓的我暫時(shí)回車忽略了, 以后可以填


7F1989D5-0352-40A5-B994-667A99F24402.png

此時(shí)在我們的xcode的info.plist中會多出一條


880D2247-34F9-4117-BE98-DE8D7A876A5B.png

在plist中添加
534778B3-1CF6-4F1F-870A-F322C4D13E6D.png

717CD9E5-8F4D-4DA2-A851-B825FADF038D.png

這個(gè)方法簡直是超級簡單
接下來我們來看看codepush給我們提供的demo(這個(gè)必須看啊).
現(xiàn)在我們直接把里面的內(nèi)容復(fù)制到index.ios.js里面,注意需要改寫東西

class codePushDemo extends Component  //這個(gè)類名字改成項(xiàng)目名(自己喜好)
//這里面都需要改成項(xiàng)目名字(當(dāng)然也可以按照你自己的習(xí)慣)
let codePushOptions = { checkFrequency: CodePush.CheckFrequency.MANUAL };
codePushDemo = CodePush(codePushOptions)(codePushDemo);
AppRegistry.registerComponent("codePushDemo", () => codePushDemo);

此時(shí)你去運(yùn)行iOS項(xiàng)目,你可能遇到這個(gè)錯(cuò)誤(如果沒有遇到最好了)

../node_modules/react-native/packager/react-native-xcode.sh: No such file or directory

我是重新安裝的node_modules解決的,文件缺失,由于也是剛接觸不久,也不知道原因,

六.打離線包

說明:
1.我們在RN項(xiàng)目根目錄下線創(chuàng)建bundle文件夾,再在bundle中創(chuàng)建創(chuàng)建ios和android文件夾,最后將生成的bundle文件和資源文件拖到我們的項(xiàng)目工程中
2.生成bundle命令 react-native bundle --platform 平臺 --entry-file 啟動文件 --bundle-output 打包js輸出文件 --assets-dest 資源輸出目錄 --dev 是否調(diào)試
給個(gè)例子??

$ react-native bundle --entry-file index.js --bundle-output ./bundle/ios/main.jsbundle --platform ios --assets-dest ./bundle/ios --dev false

七.發(fā)布更新包

將生成的bundle文件上傳到CodePush,我們直接執(zhí)行下面的命令即可

code-push release-react <Appname> <Platform> --t <本更新包面向的舊版本號> --des <本次更新說明>
注意: CodePush默認(rèn)是更新Staging 環(huán)境的,如果發(fā)布生產(chǎn)環(huán)境的更新包,需要指定--d參數(shù):--d Production,如果發(fā)布的是強(qiáng)制更新包,需要加上 --m true強(qiáng)制更新

給個(gè)例子??

$ code-push release-react wisdompark-ios ios --t 1.0.1 --dev false  --des "這是第一個(gè)更新包" --m true

發(fā)布完成之后,查看發(fā)布的歷史記錄,命令如下

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

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

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