为Hbuilder的vue2APP增加w gt热更新功能,精简版前后端代码

Hbuilder Vue2 APP 热更新(WGT)功能实现

前端实现 (Vue2)

  1. 安装必要的依赖:

    npm install md5
  2. 在main.js中添加热更新检查逻辑:

    
    import md5 from 'md5'

// 热更新检查函数
const checkUpdate = () => {
const wgtUrl = 'https://your-server.com/wgt/update.json'

plus.runtime.getProperty(plus.runtime.appid, (widgetInfo) => {
const currentVersion = widgetInfo.version
const currentMd5 = md5(currentVersion)

uni.request({
  url: wgtUrl,
  success: (res) => {
    const serverVersion = res.data.version
    const serverMd5 = md5(serverVersion)

    if (serverMd5 !== currentMd5) {
      uni.showModal({
        title: '更新提示',
        content: '发现新版本,是否下载并安装?',
        success: (e) => {
          if (e.confirm) {
            downloadInstall(res.data.url)
          }
        }
      })
    }
  }
})

})
}

// 下载并安装wgt包
const downloadInstall = (wgtUrl) => {
uni.showLoading({ title: '下载中...', mask: true })

const downloadTask = uni.downloadFile({
url: wgtUrl,
success: (downloadResult) => {
if (downloadResult.statusCode === 200) {
plus.runtime.install(downloadResult.tempFilePath, {
force: true
}, () => {
uni.hideLoading()
uni.showToast({ title: '更新成功', icon: 'success' })
plus.runtime.restart()
}, (e) => {
uni.hideLoading()
uni.showToast({ title: '更新失败', icon: 'none' })
console.error('安装失败:', e)
})
}
},
fail: (err) => {
uni.hideLoading()
uni.showToast({ title: '下载失败', icon: 'none' })
console.error('下载失败:', err)
}
})

downloadTask.onProgressUpdate((res) => {
console.log('下载进度:', res.progress)
})
}

// 应用启动时检查更新
const appLaunch = () => {
// 开发环境不检查更新
if (process.env.NODE_ENV === 'development') return

// 5秒后检查更新(避免影响启动速度)
setTimeout(checkUpdate, 5000)
}

appLaunch()


3. **在manifest.json中配置**:
```json
{
  "app-plus": {
    "distribute": {
      "android": {
        "permissions": [
          "<uses-permission android:name=\"android.permission.INTERNET\"/>",
          "<uses-permission android:name=\"android.permission.WRITE_EXTERNAL_STORAGE\"/>"
        ]
      },
      "ios": {
        "permissions": {
          "NSAppTransportSecurity": {
            "NSAllowsArbitraryLoads": true
          }
        }
      }
    }
  }
}

后端实现 (Node.js Express)

const express = require('express')
const fs = require('fs')
const path = require('path')
const md5 = require('md5')
const app = express()

// 配置静态资源目录
app.use('/wgt', express.static(path.join(__dirname, 'wgt')))

// 生成版本信息
const generateVersionInfo = () => {
  const wgtPath = path.join(__dirname, 'wgt', 'www.wgt')
  const stats = fs.statSync(wgtPath)

  return {
    version: md5(stats.mtime.toString()),
    url: 'https://your-server.com/wgt/www.wgt',
    releaseTime: stats.mtime,
    note: '修复若干bug,优化用户体验'
  }
}

// 版本检查接口
app.get('/wgt/update.json', (req, res) => {
  try {
    const versionInfo = generateVersionInfo()
    res.json({
      code: 0,
      data: versionInfo
    })
  } catch (e) {
    res.status(500).json({
      code: -1,
      message: '获取版本信息失败'
    })
  }
})

app.listen(3000, () => {
  console.log('热更新服务器运行在 http://localhost:3000')
})

使用说明

  1. 前端部署:

    • 将上述前端代码集成到你的Vue2项目中
    • 修改wgtUrl为你的实际服务器地址
  2. 后端部署:

    • 安装依赖: npm install express md5
    • 在项目根目录创建wgt文件夹
    • 将生成的www.wgt文件放入wgt文件夹
    • 启动服务器: node server.js
  3. 生成wgt文件:

    • 在HBuilder中完成开发后,点击"发行" -> "制作应用wgt包"
    • 将生成的www.wgt文件上传到服务器wgt目录
  4. 更新流程:

    • 修改代码后重新生成wgt包
    • 上传新wgt包到服务器替换旧包
    • 客户端启动时会自动检查并提示更新
所有内容均由人工智能模型生成,其生成内容的准确性和完整性无法保证,不代表我们的态度或观点。