0%

react native 如何集成热更新服务

react native 集成 hot code push。

安装 react-native-code-push包

通过yarn安装

1
yarn add react-native-code-push

或者通过npm安装

1
npm install react-native-code-push --save
1
react-native link react-native-code-push

android 安装详见

第一步

因为在开发过程中我们会使用到Staging和release的打包方式以及相对应的热更新。因此我们将热更新的 deployment key 放在 android/app/build.grade 的打包配置中,修改buildTypes如下所示:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
buildTypes {
debug {
buildConfigField "String", "CODEPUSH_KEY", '""'
}
releaseStaging {
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
signingConfig signingConfigs.release
buildConfigField "String", "CODEPUSH_KEY", '"FKqw10ptxxxxxxxxxxxxxxxxOXqog"'
}

release {
minifyEnabled enableProguardInReleaseBuilds
proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
signingConfig signingConfigs.release
buildConfigField "String", "CODEPUSH_KEY", '"BNcJv7xxxxxxxxxxxxxxxuxxxxxxxxxxxqog"'
}
}

第二步

我们定义了 CODEPUSH_KEY 这个打包config,我们需要在 android/app/src/main/com/xxxx/MainApplication.java中做如下处理

1
new CodePush("deployment-key-here", MainApplication.this, BuildConfig.DEBUG)

替换成下面

1
new CodePush(BuildConfig.CODEPUSH_KEY, MainApplication.this, BuildConfig.DEBUG)

第三步

修改versionName。
在 android/app/build.gradle中有个android.defaultConfig.versionName属性,我们需要把 应用版本改成 1.0.0。
android{
defaultConfig{
versionCode 7 // 打包次数,每次发布是需要递增1,同ios的build的版本书相类似
versionName “1.0.0” // 修改这里,默认是1.0,但是codepush需要三位数,
// 以后版本升级需要修改这里
}
}

至此android配置完成

ios 安装详见

关于deployment-key的设置
在我们想CodePush注册App的时候,CodePush会给我们两个deployment-key分别是在生产环境与测试环境时使用的,我们可以通过如下步骤来设置deployment-key。

第一步

用Xcode 打开项目 ➜ Xcode的项目导航视图中的PROJECT下选择你的项目 ➜ 选择Info页签 ➜ 在Configurations节点下单击 + 按钮 ➜ 选择Duplicate “Release ➜ 输入Staging(名称可以自定义)
创建Staging

第二步

然后选择Build Settings页签 ➜ 单击 + 按钮然后选择添加User-Defined Setting
添加User-Defined-Setting

第三步

然后输入CODEPUSH_KEY(名称可以自定义)
设置Staging deployment key
提示:你可以通过code-push deployment ls -k命令来查看deployment key。
创建CODEPUSH_KEY

第四步

打开 Info.plist文件,在CodePushDeploymentKey列的Value中输入$(CODEPUSH_KEY)
引用CODEPUSH_KEY

到目前为止,iOS的设置已经完成了。

在react-native项目中使用code-push

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
// 引入codePush
import codePush from 'react-native-code-push';

// 每一次app启动的时候进行验证。
componentDidMount() {
// 不打开询问窗口,让用户确定是否进行更新。
// 如果更新那个方式为强制更新的话(mandatory),当下载完更新包之后回自动重启应用
codePush.sync({
updateDialog: false,
mandatoryInstallMode: codePush.InstallMode.IMMEDIATE,
});

// 以下方式为有提醒窗口
/*
codePush.sync({
updateDialog: {
appendReleaseDescription: true,
descriptionPrefix: '更新内容:\n',
title: '更新',
mandatoryUpdateMessage: '',
mandatoryContinueButtonLabel: '更新',
optionalIgnoreButtonLabel: '取消',
optionalInstallButtonLabel: '安装',
optionalUpdateMessage: '',
},
mandatoryInstallMode: codePush.InstallMode.IMMEDIATE,
// deploymentKey: CODE_PUSH_PRODUCTION_KEY,
});
*/
}

更多详细细节可以查看React Native应用部署/热更新-CodePush最新集成总结(新)这篇文章