1
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?

【Vite + React】ローカル開発で画面が表示されない問題を解決した話

Posted at

はじめに

【時間がない方向け】
4.まで読み飛ばして解決策をチェックしてください!

Vite + React でローカル開発をしていた際に、ブラウザで localhost にアクセスしても画面が表示されないという問題に遭遇しました。

最終的に index.html をルートディレクトリに移動することで解決しましたが、その過程で試したことや気づいた点をまとめます。


問題発生

現象

Vite を起動しても、ブラウザで http://localhost:5174/ にアクセスすると画面が真っ白で何も表示されない。

環境

  • OS: Ubuntu 22.04(WSL2)
  • Node.js: v18.x
  • Vite: v4.0
  • React: v18.x

ディレクトリ構成(エラー発生時)

my_pjt/
├── frontend/
│   ├── public/
│   │   ├── index.html
│   │   ├── favicon.ico
│   │   ├── assets/
│   ├── src/
│   │   ├── App.tsx
│   │   ├── main.tsx
│   ├── vite.config.ts

ポイント

  • index.htmlpublic/ に配置していた
  • vite.config.tspublicDir"/public" に指定していた

試したことと結果

1. Vite の開発サーバーを再起動

npm run dev

→ 変化なし(画面は依然として真っ白)

2. ブラウザの開発者ツールを確認

  • F12Console を確認すると、Failed to load resource: the server responded with a status of 404 (Not Found)
  • Network タブで index.html のリクエストが 404 Not Found になっていた

→ Vite が index.html を正しく読み込めていない可能性があると判明

3. Vite の publicDir の設定を変更

変更前(エラー発生時の設定)

export default defineConfig({
  plugins: [react()],
  root: ".",
  publicDir: "/public",  // これが問題かも?
  server: {
    host: "0.0.0.0",
    port: 5174,
    strictPort: false,
  },
});

変更後

export default defineConfig({
  plugins: [react()],
  root: ".",
  server: {
    host: "0.0.0.0",
    port: 5174,
    strictPort: false,
  },
});

publicDir の設定を削除し、Vite のデフォルト動作(public/ を自動認識)に戻す。

→ 変化なし(依然として index.html が読み込まれない)

4. index.html をルートに移動(解決策!)

ディレクトリ構成(修正後)

my_pjt/
├── frontend/
│   ├── index.html  ← ルートに移動
│   ├── public/
│   │   ├── favicon.ico
│   │   ├── assets/
│   ├── src/
│   │   ├── App.tsx
│   │   ├── main.tsx
│   ├── vite.config.ts

結果

npm run dev で開発サーバーを起動した後、

npm run dev

ブラウザで http://localhost:5174/ にアクセスすると…

🎉 無事に Hello, Vite + React! が表示された!


考察:なぜ index.html をルートに置く必要があったのか?

Vite の仕様上、index.htmlプロジェクトのルートディレクトリに配置されている必要がある ため。

  • Vite は public/ ディレクトリを「静的ファイル専用のフォルダ」として扱う。
  • public/ 内の index.html はエントリーポイントとして認識されない。←これを知らず、時間がかかった
  • そのため、index.html をプロジェクトのルート (frontend/) に移動することで解決。

結論と学び

✔ まとめ

試したこと 結果
開発サーバーを再起動 ❌ 変化なし
開発者ツールで 404 エラーを確認 index.html が読み込まれていないと判明
vite.config.tspublicDir 設定を修正 ❌ 変化なし
index.html をルートに移動 成功! 🎉

✔ 今後の対策

  • Vite では index.html はルートに配置する
  • public/ は静的リソース専用(画像、フォント、favicon など)
  • 開発時に F12 → ConsoleNetwork タブでエラーを確認

おわりに

今回は index.html の配置ミスが原因で、画面が表示されない問題に直面しました。

Vite の仕様を正しく理解していればすぐに解決できた問題ですが、いい勉強になりました。

同じ問題で困っている方の参考になれば嬉しいです!🙌

1
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
1
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?