コフス技術ブログ

ViteでカスタムHMRを利用する

Viteにて、public/配下に設置したjsonファイルを変更したタイミングでもhot module replacement(以下HMR)したかったので、カスタムHMRを利用した際の備忘録です。

まずは新たにViteのプラグインとしてreact-hmr.tsを用意します。
handleHotUpdateでカスタムHMR処理を行えますが、今回はjsonファイルの変更をトリガーにしたいのでfile.endsWithで更新ファイルが.jsonの時のみserver.ws.sendする形にします。

handleHotUpdateの型を表示
interface HmrContext {
  file: string
  timestamp: number
  modules: Array<ModuleNode>
  read: () => string | Promise<string>
  server: ViteDevServer
}

handleHotUpdate(ctx: HmrContext) => Array<ModuleNode> | void | Promise<Array<ModuleNode> | void>

詳細: https://ja.vitejs.dev/guide/api-plugin.html#handlehotupdate

react-hmr.ts
import { PluginOption } from 'vite'

const CustomHmr = (): PluginOption => {
  return {
    name: 'custom-hmr',
    enforce: 'post',
    // HMR
    handleHotUpdate({ file, server }) {
      if (file.endsWith('.json')) {
        console.log('reloading json file...')

        server.ws.send({ type: 'full-reload', path: '*' })
      }
    }
  }
}

export default CustomHmr

あとは以下でプラグインをvite.configに追加し利用するだけです。

vite.config.ts
import { defineConfig, UserConfig } from 'vite'

import hmr from './react-hmr'

// https://vitejs.dev/config/
const config: UserConfig = {
  plugins: [
    hmr()
  ]
}

export default defineConfig(config)