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?

Viteで始める高速Web開発 | 第2章: プロジェクト構造と仕組み

Posted at

はじめに

第1章でViteの基本と初期設定を学びました。今回は、Viteのプロジェクト構造を詳しく見て、その仕組みを理解します。Reactを使った簡単なページを作りながら、Viteの特徴を体験します。

目標

  • Viteのプロジェクト構造を把握する
  • 開発サーバーとビルドプロセスの仕組みを知る
  • 簡単なページを作成する

Viteのプロジェクト構造

Viteプロジェクトのデフォルト構造は以下の通り:

my-vite-app/
  ├── node_modules/       # 依存関係
  ├── public/            # 静的ファイル
  │   └── vite.svg       # サンプル画像
  ├── src/               # ソースコード
  │   ├── App.jsx        # メインコンポーネント
  │   ├── main.jsx       # アプリのエントリー
  │   └── index.css      # グローバルスタイル
  ├── index.html         # HTMLテンプレート
  ├── package.json       # 依存関係とスクリプト
  ├── vite.config.js     # Vite設定ファイル
  • index.html: アプリの基盤。<script type="module">main.jsxを読み込み。
  • src/main.jsx: Reactを初期化し、App.jsxをレンダリング。
  • vite.config.js: サーバーやビルドの設定をカスタマイズ。

Viteの仕組み

開発サーバー

Viteは、ブラウザのネイティブES Modulesを活用します。従来のツール(例: Webpack)のように開発時に全てをバンドルせず、必要なモジュールだけをオンデマンドで提供。これにより、起動と更新が高速です。

試しにsrc/App.jsxを編集し保存すると、Hot Module Replacement(HMR)で即座に反映されます。

ビルドプロセス

本番用ビルドでは、Rollupが使われます。コマンドは:

npm run build

生成されたdist/フォルダには、最適化されたファイルが出力されます。プレビューするには:

npm run preview

vite.config.jsの基本設定

vite.config.jsを開き、簡単なカスタマイズを試します:

export default {
  server: {
    port: 3000, // デフォルトポートを変更
  },
  base: '/my-app/', // 本番時のベースパス
};

npm run devを再実行すると、http://localhost:3000で動作します。

簡単なページの作成

src/App.jsxを以下に更新して、シンプルなページを作ります:

import './App.css';

function App() {
  return (
    <div className="App">
      <header>
        <h1>Viteで作るページ</h1>
      </header>
      <main>
        <p>こんにちは、Viteの世界へようこそ!</p>
      </main>
      <footer>
        <p>© 2025 Vite入門</p>
      </footer>
    </div>
  );
}

export default App;

src/App.cssを更新:

.App {
  text-align: center;
  font-family: Arial, sans-serif;
}

header {
  background-color: #282c34;
  padding: 20px;
  color: white;
}

main {
  padding: 20px;
}

footer {
  background-color: #f1f1f1;
  padding: 10px;
}

動作確認

npm run devで起動し、http://localhost:3000を確認。ヘッダー、本文、フッターが表示されれば成功です。

次回予告

第3章では、ViteでReactを本格的に使い、動的なUIを作ります。お楽しみに!


この記事が役に立ったら、ぜひ「いいね」や「ストック」をお願いします!質問や感想はコメント欄で気軽にどうぞ。次回も一緒に学びましょう!

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?