跳至內容

HMR hotUpdate 外掛鉤子

意見回饋

環境 API 意見回饋討論中給我們意見回饋

我們計畫棄用 handleHotUpdate 外掛鉤子,改用hotUpdate 鉤子,使其能感知環境 API,並使用 createdelete 處理額外的監看事件。

影響範圍:Vite 外掛作者

未來棄用

hotUpdate 最早於 v6.0 中引入。handleHotUpdate 的棄用計畫於 v7.0 實施。我們目前不建議捨棄 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 []
}

根據 MIT 許可證發布。(ccee3d7c)