HMR hotUpdate
插件钩子
反馈
请在环境 API 反馈讨论中给我们反馈
我们计划废弃 handleHotUpdate
插件钩子,转而使用hotUpdate
钩子,以便更好地感知环境 API,并处理 create
和 delete
等额外的监听事件。
受影响范围:Vite 插件作者
未来废弃
hotUpdate
最初在 v6.0
中引入。handleHotUpdate
的废弃计划在未来的一个主要版本中进行。我们目前不建议立即从 handleHotUpdate
迁移。如果你想试验并提供反馈,可以在 Vite 配置中使用 future.removePluginHookHandleHotUpdate
并将其设置为 "warn"
。
动机
handleHotUpdate
钩子允许执行自定义的 HMR 更新处理。一个模块列表会在 HmrContext
中传递。
ts
interface HmrContext {
file: string
timestamp: number
modules: Array<ModuleNode>
read: () => string | Promise<string>
server: ViteDevServer
}
此钩子对所有环境只调用一次,并且传递的模块只包含来自客户端和 SSR 环境的混合信息。一旦框架迁移到自定义环境,就需要一个为每个环境调用的新钩子。
新的 hotUpdate
钩子工作方式与 handleHotUpdate
相同,但它会为每个环境调用,并接收一个新的 HotUpdateOptions
实例。
ts
interface HotUpdateOptions {
type: 'create' | 'update' | 'delete'
file: string
timestamp: number
modules: Array<EnvironmentModuleNode>
read: () => string | Promise<string>
server: ViteDevServer
}
当前开发环境可以像其他插件钩子一样通过 this.environment
访问。modules
列表现在将仅包含当前环境的模块节点。每个环境更新可以定义不同的更新策略。
此外,此钩子现在也会为额外的监听事件调用,而不仅仅是 'update'
。使用 type
来区分它们。
迁移指南
过滤并缩小受影响的模块列表,使 HMR 更准确。
js
handleHotUpdate({ modules }) {
return modules.filter(condition)
}
// Migrate to:
hotUpdate({ modules }) {
return modules.filter(condition)
}
返回一个空数组并执行完全重新加载
js
handleHotUpdate({ server, modules, timestamp }) {
// Invalidate modules manually
const invalidatedModules = new Set()
for (const mod of modules) {
server.moduleGraph.invalidateModule(
mod,
invalidatedModules,
timestamp,
true
)
}
server.ws.send({ type: 'full-reload' })
return []
}
// Migrate to:
hotUpdate({ modules, timestamp }) {
// Invalidate modules manually
const invalidatedModules = new Set()
for (const mod of modules) {
this.environment.moduleGraph.invalidateModule(
mod,
invalidatedModules,
timestamp,
true
)
}
this.environment.hot.send({ type: 'full-reload' })
return []
}
返回一个空数组并通过向客户端发送自定义事件来执行完整的自定义 HMR 处理
js
handleHotUpdate({ server }) {
server.ws.send({
type: 'custom',
event: 'special-update',
data: {}
})
return []
}
// Migrate to...
hotUpdate() {
this.environment.hot.send({
type: 'custom',
event: 'special-update',
data: {}
})
return []
}