在微信小程序中实现代码自动更新,主要利用小程序提供的更新机制API,以下是详细实现方案和代码:
App({
onLaunch() {
this.checkUpdate()
},
// 检查更新
checkUpdate() {
if (!wx.canIUse('getUpdateManager')) {
console.warn('当前微信版本过低,不支持更新')
return
}
const updateManager = wx.getUpdateManager()
// 监听检查更新结果
updateManager.onCheckForUpdate(res => {
if (!res.hasUpdate) return
console.log('检测到新版本,开始下载...')
})
// 新版本下载完成
updateManager.onUpdateReady(() => {
wx.showModal({
title: '更新提示',
content: '新版本已准备好,是否立即重启应用?',
success: res => {
if (res.confirm) {
// 应用新版本并重启
updateManager.applyUpdate()
}
}
})
})
// 更新失败处理
updateManager.onUpdateFailed(() => {
wx.showModal({
title: '更新失败',
content: '新版本下载失败,请检查网络后重新进入小程序',
showCancel: false
})
})
}
})
// app.js 中修改 onUpdateReady 部分
updateManager.onUpdateReady(() => {
wx.showModal({
title: '强制更新',
content: '本次更新包含重要功能,请立即重启',
showCancel: false, // 隐藏取消按钮
confirmText: '立即重启',
success: res => {
if (res.confirm) {
updateManager.applyUpdate()
}
}
})
})
// 记录用户忽略更新的版本
const IGNORE_VERSION_KEY = 'ignoreVersion'
updateManager.onUpdateReady(() => {
const { version } = __wxConfig.envVersion // 当前运行版本
const ignoredVersion = wx.getStorageSync(IGNORE_VERSION_KEY)
// 如果用户已忽略当前版本
if (ignoredVersion === version) return
wx.showModal({
title: '更新提示',
content: `发现新版本 ${version}`,
confirmText: '重启',
cancelText: '暂不更新',
success: res => {
if (res.confirm) {
updateManager.applyUpdate()
} else {
wx.setStorageSync(IGNORE_VERSION_KEY, version) // 记录忽略版本
}
}
})
})
发布流程:
版本同步:
测试技巧:
project.config.json
的 version
模拟更新更新频率:
用户提醒:
// 添加更新动画
wx.showLoading({
title: '更新中...',
mask: true
})
updateManager.applyUpdate({
success: () => wx.hideLoading()
})
错误监控:
updateManager.onUpdateFailed(() => {
wx.reportAnalytics('update_failed', {
version: __wxConfig.envVersion
})
})
官方限制:小程序包大小不能超过 20MB(分包总计),更新时只会下载差异部分,可有效减小下载体积。
通过以上实现,用户首次打开新版本时会看到更新提示,之后再次进入时会自动加载最新代码,实现无缝更新体验。