MeWrite Docs

[vite] Failed to reload - HMR update failed

ViteのHot Module Replacement (HMR) が失敗した場合のエラー

概要

ViteのHot Module Replacement (HMR) が正常に動作しない場合に発生するエラーです。ファイル変更時にブラウザが自動更新されなくなります。

エラーメッセージ

[vite] Failed to reload /src/components/App.tsx. This could be due to syntax errors or importing non-existent modules.
[vite] Internal server error: Failed to resolve import "@/components/Button" from "src/App.tsx". Does the file exist?
[vite] hmr invalidate /src/main.tsx Could not Fast Refresh.

原因

1. 構文エラー

2. 存在しないモジュールのインポート

3. 循環依存

4. ファイルシステムの大文字小文字の問題

5. React Fast Refreshの制限

解決策

1. 構文エラーを修正

1
2
3
4
5
# ESLintで構文チェック
npx eslint src/

# TypeScriptの型チェック
npx tsc --noEmit

2. インポートパスを確認

1
2
3
4
5
// NG: 存在しないパス
import { Button } from '@/components/Button'

// OK: 正しいパス
import { Button } from './components/Button'

3. エイリアスの設定を確認

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
// vite.config.ts
import { defineConfig } from 'vite'
import path from 'path'

export default defineConfig({
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src'),
    },
  },
})
1
2
3
4
5
6
7
8
9
// tsconfig.json
{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    }
  }
}

4. React Fast Refreshの制限に対処

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// NG: 名前付きエクスポートと default エクスポートの混在
export const Button = () => <button>Click</button>
export default function App() { return <div /> }

// OK: コンポーネントのみをエクスポート
export default function App() {
  return <div><Button /></div>
}

function Button() {
  return <button>Click</button>
}

5. ファイル名の大文字小文字を統一

1
2
3
4
5
6
7
8
# macOS/Windowsでは大文字小文字を区別しないことがある
# Linux(CI/本番)では区別される

# NG
import Header from './header'  // ファイル名は Header.tsx

# OK
import Header from './Header'

6. HMRの設定を調整

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
// vite.config.ts
export default defineConfig({
  server: {
    hmr: {
      overlay: true,
      // WebSocket接続の問題がある場合
      host: 'localhost',
      port: 5173,
    },
    watch: {
      // ファイル監視の問題がある場合
      usePolling: true,
      interval: 100,
    },
  },
})

7. キャッシュをクリア

1
2
3
4
5
# node_modulesの.viteを削除
rm -rf node_modules/.vite

# 開発サーバーを再起動
npm run dev

8. 循環依存を解消

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// NG: 循環依存
// a.ts
import { b } from './b'
export const a = () => b()

// b.ts
import { a } from './a'
export const b = () => a()

// OK: 依存関係を整理
// utils.ts(共通部分を抽出)
export const shared = () => {}

WSL2での問題

1
2
3
4
5
6
7
8
9
// vite.config.ts
export default defineConfig({
  server: {
    watch: {
      // WSL2でのファイル監視問題
      usePolling: true,
    },
  },
})

デバッグ方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
// vite.config.ts
export default defineConfig({
  // 詳細なログを出力
  logLevel: 'info',
  server: {
    hmr: {
      overlay: true,
    },
  },
})

関連エラー

関連エラー

Vite の他のエラー

最終更新: 2025-12-18