vue实现上线热更新
Vue 实现上线热更新
热更新(Hot Module Replacement, HMR)允许在不刷新页面的情况下替换、添加或删除模块,提升开发效率。以下是实现 Vue 项目热更新的方法:
开发环境热更新
Vue CLI 或 Vite 创建的项目默认支持 HMR,无需额外配置。
// vite.config.js
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
export default defineConfig({
plugins: [vue()]
})
生产环境热更新
生产环境热更新需结合后端服务或工具实现:
方法一:使用 WebSocket 通信
- 前端监听服务端推送的更新消息:
// main.js const socket = new WebSocket('ws://your-server-address')
socket.addEventListener('message', (event) => { if (event.data === 'update') { window.location.reload() } })
2. 服务端检测文件变化后推送消息:
```javascript
// Node.js 示例
const WebSocket = require('ws')
const chokidar = require('chokidar')
const wss = new WebSocket.Server({ port: 8080 })
chokidar.watch('./dist').on('change', () => {
wss.clients.forEach(client => client.send('update'))
})
方法二:使用 Service Worker
通过 Workbox 实现动态缓存更新:
// sw.js
import { precacheAndRoute } from 'workbox-precaching'
precacheAndRoute(self.__WB_MANIFEST)
self.addEventListener('message', (event) => {
if (event.data.action === 'skipWaiting') {
self.skipWaiting()
}
})
方法三:使用插件实现
安装 vite-plugin-hot-update 等插件:
// vite.config.js
import hotUpdate from 'vite-plugin-hot-update'
export default {
plugins: [
hotUpdate({
watchDir: 'dist',
watchOptions: { ignoreInitial: true }
})
]
}
注意事项
- 生产环境热更新需考虑版本兼容性和回滚机制
- 静态资源需配置正确的缓存策略(如
Cache-Control: no-cache) - 建议在更新前提示用户保存数据
完整示例
结合 WebSocket 的 Vue 热更新实现:
// 前端代码
mounted() {
this.setupWebSocket()
},
methods: {
setupWebSocket() {
const protocol = location.protocol === 'https:' ? 'wss:' : 'ws:'
const ws = new WebSocket(`${protocol}//${location.host}/ws-update`)
ws.onmessage = (e) => {
if (e.data === 'reload') {
setTimeout(() => {
window.location.reload()
}, 1000)
}
}
}
}
以上方法可根据实际项目需求选择或组合使用。







