React-Native的codepush配置

1,389 阅读7分钟

一. Android 客户端环境搭建

前置条件

  • react-native版本: 0.61+
  • node版本: 12.10.0+

react native 0.60版本及以上会自动link第三方库,如果我们执行 了 yarn add react-native-code-push 。

android环境会自动配置好code-push的配置文件,

但是我们搭建的是私有服务器的热更新需要手动配置请求热更新的地址,因此,我们需要禁用react-native-code-push  在android环境中的自动配置

1. 初始化RN项目 

创建一个RN的练手项目,然后配置上面获取到的Deployment Key 配置

$react-native init HotUpdateDemo
$ cd ./HotUpdateDemo
$ npm install --save react-native-code-push  #安装react-native-code-push

2. 禁用 react-native-code-push  在android环境中的自动配置(autoLink)

在项目根目录新建 react-native.config.js 加入以下内容

module.exports = {
  dependencies: {
    "react-native-code-push": {
      platforms: {
        android: null
      }
    }
  }
};

3. Android环境配置

官方文档

3.1 android/app/build.gradle修改

// 省略号............
// 如果已经存在react.gradle则不需要重复引入    
apply from: "../../node_modules/react-native/react.gradle"
apply from: "../../node_modules/react-native-code-push/android/codepush.gradle"
    
// 省略号............
 ............    
    
dependencies {
	......
    // implementation "com.facebook.react:react-native:0.61.5"   // From node_modules
    implementation project(path: ':react-native-code-push')  // From node_modules
    ......
    }    
 ............

3.2 android/settings.gradle修改

............
rootProject.name = '当前app的名字'
// 重要的是下面两行代码
include ':react-native-code-push'
project(':react-native-code-push').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-code-push/android/app')

............
............
apply from: file("../node_modules/@react-native-community/cli-platform-android/native_modules.gradle"); applyNativeModulesSettingsGradle(settings)
include ':app'
............

3.3 配置 开发/生产环境的deploymentKey

进入  android\app\src\main\res\values\strings.xml  ,加入以下代码

可以通过 code-push deployment ls <appName> -k  命令获取不同环境的DeploymentKey

<resources>
		............
        ............
     <string moduleConfig="true" name="CodePushDeploymentKeyTest">测试环境的DeploymentKey</string>
     <string moduleConfig="true" name="CodePushDeploymentKeyPro">生产环境的DeploymentKey</string>
    	............
        ............
</resources>
 

3.4 MainApplication.java修改

package com.beesrv.www;

............
// 导入codePush包
import com.microsoft.codepush.react.CodePush;
............

public class MainApplication extends Application implements ReactApplication {
  private final ReactNativeHost mReactNativeHost =
      new ReactNativeHost(this) {
		............
        ............
       // 加入这个代码
        @Override
        protected String getJSMainModuleName() {
          return "index";
        }
       	// 加入这个代码
        @Override
        protected String getJSBundleFile() {
            return CodePush.getJSBundleFile();
        }  
        @Override
        protected List<ReactPackage> getPackages() {
          @SuppressWarnings("UnnecessaryLocalVariable")
          List<ReactPackage> packages = new PackageList(this).getPackages();
            
          // String deploymentKey, Context context, boolean isDebugMode, String serverUrl
          /*
          	deploymentKey 为当前环境(测试环境/生产环境)的热更新key,
            serverUrl 为热更新私有服务器地址  如:http://45.40.193.123:3000
          */              
		  // 加入这个代码
          packages.add(new CodePush("deploymentKey",MainApplication.this,BuildConfig.DEBUG,"serverUrl"));
          return packages;
        }
		............
        ............
      };
}

3. 在RN中添加热更新代码

打开React Native的入口文件index.js,并对index.js文件进行如下的修改

import React, {Component} from 'react';
import {AppRegistry, Platform, StyleSheet, Text, View} from 'react-native';
import {name as appName} from './app.json';
import codePush from 'react-native-code-push'

type Props = {};
export default class App extends Component<Props> {

    constructor(props) {
        super(props);
        this.state = {
            message: ''
        };
    }

    componentDidMount() {
        codePush.checkForUpdate().then((update) => {
            if (update) {
                this.setState({message: '有新的更新!'})
            } else {
                this.setState({message: '已是最新,不需要更新!'})
            }
        })
    }

    render() {
        return (
            <View style={styles.container}>
                <Text style={styles.welcome}>版本号 1.0</Text>
                <Text style={styles.instructions}>{this.state.message}</Text>
            </View>
        );
    }
}

//省略样式文件

AppRegistry.registerComponent(appName, () => codePush(App));

可以componentDidMount生命周期函数会检查CodePush应用是否需要更新,如果检测需要更新则下载CodePush应用的更新。重新编译和运行应用

将index.js文件显示的版本号升级为1.1,修改内容如下

render() {
        return (
            <View style={styles.container}>
                <Text style={styles.welcome}>版本号 1.1</Text>
                <Text style={styles.instructions}>{this.state.message}</Text>
            </View>
        );
    }

4. 生成bundle

发布更新之前,需要先把 js打包成 bundle,如:

  • 第一步: 在 工程目录里面新增 bundles文件:mkdir bundles
  • 第二步: 运行命令打包 react-native bundle --platform 平台 --entry-file 启动文件 --bundle-output 打包js输出文件 --assets-dest 资源输出目录 --dev 是否调试

eg: react-native bundle --platform android --entry-file index.android.js --bundle-output ./bundles/index.android.bundle --dev false

// 离线包
 $ cd ./工程目录
 $ mkdir bundles
 $ react-native bundle --platform 平台 --entry-file 启动文件 --bundle-output 打包js输出文件 --assets-dest 资源输出目录 --dev 是否调试。
 eg.
 $react-native bundle --platform ios --entry-file index.js --bundle-output ./ios/bundles/main.jsbundle --dev false
react-native bundle --platform 平台 --entry-file 启动文件 --bundle-output 打包js输出文件 --assets-dest 资源输出目录 --dev 是否调试

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

5. 发布更新

打包bundle结束后,就可以通过CodePush发布更新了。在终端输入

code-push release <应用名称> <Bundles所在目录> <对应的应用版本> --deploymentName: 更新环境 --description: 更新描述 --mandatory: 是否强制更新

eg: code-push release GitHubPopular ./bundles/index.android.bundle 1.0.6 --deploymentName Production --description "1.支持文章缓存。" --mandatory true


 $ code-push release <应用名称> <Bundles所在目录> <对应的应用版本> --deploymentName: 更新环境 --description: 更新描述 --mandatory: 是否强制更新 
code-push release HotUpdateDemo-ios ./ios/bundles/main.jsbundle 1.0.0 --deploymentName Production --description "我是新包,很新的那种" --mandatory true  
 

 $ code-push release-react <Appname> <Platform> --t <本更新包面向的旧版本号> --des <本次更新说明>
 注意: CodePush默认是更新Staging 环境的,如果发布生产环境的更新包,
 需要指定--d参数:--d Production,
 如果发布的是强制更新包,需要加上 --m true强制更新
 $ code-push release-react iOSRNHybrid ios --t 1.0.0 --dev false --d Production --des "这是第一个更新包" --m true

6. 最简单的方式(可以忽略)

   融合简化了上诉第四,第五步操作 (自动生成build&自动发布)

code-push release-react <appname> <plateform>
  
测试环境执行:
$ code-push release-react 项目名-android android
生产环境执行:
$ code-push release-react 项目名-android android -d Production

code-push release-react MyApp-iOS ios  --t 1.0.0 --dev false --d Production --des "1.优化操作流程" --m true

其中参数
--t为二进制(.ipa与apk)安装包的的版本;
--dev为是否启用开发者模式(默认为false);
--d是要发布更新的环境分Production与Staging(默认为Staging);
--des为更新说明;
--m 是强制更新。

发布更新包命令中的 
-- t 对应的参数是和我们项目中的版本号一致的,这个不要误理解为是更新包的版本号,
例如项目中的版本号为1.0.0, 这时如果我们需要对这个1.0.0 版本的项目进行第一次热更新,
那么命令中的 -- t 也为1.0.0,第二次热更新任然为1.0.0

项目的版本号需要改为三位的,默认是两位的,但是CodePush需要三位数的版本号

发布更新应用时,应用的名称必须要和之前注册过的应用名称一致

关于code-push release-react更多可选的参数,可以在终端输入code-push release-react进行查看。

另外,我们可以通过code-push deployment ls <appName>来查看发布详情与此次更新的安装情况。

 eg:code-push release-react codepushAPP ios

等待系统打包并发布热更新的bundle文件,发布成功后关闭并重新打开应用,就可以看到应用启动时会提示更新

在检测到更新后,系统会下载最新的资源并更新,当再次关闭并重新打开应用时,可以看到应用更新成功后的效果。并且,还可以使用CodePush提供的code-push deployment命令来查看更新情况,

二 . IOS客户端搭建

暂无

三. react-native代码demo

import React, { Component } from 'react';
import {
  Platform,
  StyleSheet,
  Text,
  View
} from 'react-native';

import CodePush from "react-native-code-push"; // 引入code-push

let codePushOptions = {
  //设置检查更新的频率
  //ON_APP_RESUME APP恢复到前台的时候
  //ON_APP_START APP开启的时候
  //MANUAL 手动检查
  checkFrequency : CodePush.CheckFrequency.ON_APP_RESUME
};

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

type Props = {};

class App extends Component<Props> {

  //如果有更新的提示
  syncImmediate() {
    CodePush.sync( {
          //安装模式
          //ON_NEXT_RESUME 下次恢复到前台时
          //ON_NEXT_RESTART 下一次重启时
          //IMMEDIATE 马上更新
          installMode : CodePush.InstallMode.IMMEDIATE ,
          //对话框
          updateDialog : {
            //是否显示更新描述
            appendReleaseDescription : true ,
            //更新描述的前缀。 默认为"Description"
            descriptionPrefix : "更新内容:" ,
            //强制更新按钮文字,默认为continue
            mandatoryContinueButtonLabel : "立即更新" ,
            //强制更新时的信息. 默认为"An update is available that must be installed."
            mandatoryUpdateMessage : "必须更新后才能使用" ,
            //非强制更新时,按钮文字,默认为"ignore"
            optionalIgnoreButtonLabel : '稍后' ,
            //非强制更新时,确认按钮文字. 默认为"Install"
            optionalInstallButtonLabel : '后台更新' ,
            //非强制更新时,检查到更新的消息文本
            optionalUpdateMessage : '有新版本了,是否更新?' ,
            //Alert窗口的标题
            title : '更新提示'
          } ,
        } ,
    );
  }

  componentWillMount() {
    CodePush.disallowRestart();//禁止重启
    this.syncImmediate(); //开始检查更新
  }

  componentDidMount() {
    CodePush.allowRestart();//在加载完了,允许重启
  }

  render() {
    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text style={styles.instructions}>
          To get started, edit App.js
        </Text>
        <Text style={styles.instructions}>
          {instructions}
        </Text>

        <Text style={styles.instructions}>
          这是更新的版本
        </Text>
      </View>
    );
  }
}

// 这一行必须要写
App = CodePush(codePushOptions)(App)

export default App

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
  instructions: {
    textAlign: 'center',
    color: '#333333',
    marginBottom: 5,
  },
})

在使用之前需要考虑的是检查更新时机,更新是否强制,更新是否要求即时等

更新时机

一般常见的应用内更新时机分为两种,一种是打开App就检查更新,一种是放在设置界面让用户主动检查更新并安装

  • 打开APP就检查更新 最为简单的使用方式在React Natvie的根组件的componentDidMount方法中通过

codePush.sync()(需要先导入codePush包:import codePush from 'react-native-code-push')方法检查并安装更新,如果有更新包可供下载则会在重启后生效。不过这种下载和安装都是静默的,即用户不可见。如果需要用户可见则需要额外的配置。具体可以参考codePush官方API文档,部分代码,完整代码请参照文档上面

codePush.sync({
  updateDialog: {
    appendReleaseDescription: true,
    descriptionPrefix:'\n\n更新内容:\n',
    title:'更新',
    mandatoryUpdateMessage:'',
    mandatoryContinueButtonLabel:'更新',
  },
  mandatoryInstallMode:codePush.InstallMode.IMMEDIATE,
  deploymentKey: CODE_PUSH_PRODUCTION_KEY,
});
  • 上面的配置在检查更新时会弹出提示对话框, mandatoryInstallMode表示强制更新,appendReleaseDescription表示在发布更新时的描述会显示到更新对话框上让用户可见
  • 用户点击检查更新按钮 在用户点击检查更新按钮后进行检查,如果有更新则弹出提示框让用户选择是否更新,如果用户点击立即更新按钮,则会进行安装包的下载(实际上这时候应该显示下载进度,这里省略了)下载完成后会立即重启并生效(也可配置稍后重启),部分代码如下
codePush.checkForUpdate(deploymentKey).then((update) => {
    if (!update) {
        Alert.alert("提示", "已是最新版本--", [
            {
                text: "Ok", onPress: () => {
                console.log("点了OK");
            }
            }
        ]);
    } else {
        codePush.sync({
                deploymentKey: deploymentKey,
                updateDialog: {
                    optionalIgnoreButtonLabel: '稍后',
                    optionalInstallButtonLabel: '立即更新',
                    optionalUpdateMessage: '有新版本了,是否更新?',
                    title: '更新提示'
                },
                installMode: codePush.InstallMode.IMMEDIATE,
            },
            (status) => {
                switch (status) {
                    case codePush.SyncStatus.DOWNLOADING_PACKAGE:
                        console.log("DOWNLOADING_PACKAGE");
                        break;
                    case codePush.SyncStatus.INSTALLING_UPDATE:
                        console.log(" INSTALLING_UPDATE");
                        break;
                }
            },
            (progress) => {
                console.log(progress.receivedBytes + " of " + progress.totalBytes + " received.");
            }
        );
    }
 }

更新是否强制

如果是强制更新需要在发布的时候指定,发布命令中配置--m true

更新是否要求即时

在更新配置中通过指定installMode来决定安装完成的重启时机,亦即更新生效时机

  • codePush.InstallMode.IMMEDIATE :安装完成立即重启更新
  • codePush.InstallMode.ON_NEXT_RESTART :安装完成后会在下次重启后进行更新
  • codePush.InstallMode.ON_NEXT_RESUME :安装完成后会在应用进入后台后重启更新

示例2

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 * @flow
 */

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

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

//var Dimensions = require('Dimensions');

const instructions = Platform.select({
  ios: 'Press Cmd+R to reload,\n' +
    'Cmd+D or shake for dev menu',
  android: 'Double tap R on your keyboard to reload,\n' +
    'Shake or press menu button for dev menu',
});

export default class App extends Component<{}> {

  constructor() {
    super();
    this.state = { restartAllowed: true ,
                   syncMessage: "我是小更新" ,
                   progress: false};
  }

  // 监听更新状态
  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.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}>
         可以修改此处文字,查看是否更新成功!
        </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}
        
        <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: "#F5FCFF",
    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
  },
});

参考文档