0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

HMR/hot updateをtoggleするvite plugin

Posted at

リロードの粒度をマニュアル操作したい場合に dev serverの /toggle-hmr にリクエストするとHMR/hot updateのon/off状態を切り替えられるvite pluginです。

import type {Plugin} from 'vite';

let hmrEnabled = true; // HMR の状態を記録

export function toggleHMR(): Plugin {
  return {
    name: 'toggle-hmr',
    // ミドルウェアを追加
    configureServer: (server) => {
      server.middlewares.use((req, res, next) => {
        if (req.url === '/toggle-hmr') {
          hmrEnabled = !hmrEnabled;

          // クライアントに HMR 状態を送信
          server.ws.send({
            type: 'custom',
            event: 'hmr-status',
            data: { enabled: hmrEnabled },
          });

          console.log(`HMR is now ${hmrEnabled ? 'enabled' : 'disabled'}`);
          res.end();
        } else {
          next();
        }
      });
    },
    handleHotUpdate: () => {
      if (!hmrEnabled) {
        console.log(`HMR is disabled. Skipping update`);
        return [];
      }
    },
  };
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?