1
2

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は通常シングルページアプリ(SPA)に使われますが、マルチエントリーポイントを設定することで、複数の独立したページを持つアプリも効率的に開発できます。この記事では、マルチエントリーポイントを活用し、管理画面と公開ページを持つアプリを作ります。

マルチエントリーポイントとは?

マルチエントリーポイントは、1つのプロジェクトで複数のHTMLファイルをエントリーとして管理する手法です。

  • 利点: ページごとに異なるコードを分離、独立したデプロイが可能。
  • 活用例: ダッシュボードとランディングページを1つのリポジトリで管理。

プロジェクトの準備

ReactベースのViteプロジェクトを用意:

npm create vite@latest my-multi-entry -- --template react
cd my-multi-entry
npm install

HTMLエントリーの追加

  • index.html(デフォルト)をランディングページに。
  • 新規にdashboard.htmlを作成:
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>ダッシュボード</title>
  </head>
  <body>
    <div id="root"></div>
    <script type="module" src="/src/dashboard.jsx"></script>
  </body>
</html>

設定のカスタマイズ

1. エントリーポイントの設定

vite.config.tsを更新:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  build: {
    rollupOptions: {
      input: {
        main: './index.html',
        dashboard: './dashboard.html',
      },
    },
  },
});

2. 各エントリーのコード

  • src/main.jsx(ランディングページ用):
import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <div>
      <h1>ランディングページ</h1>
      <p>ようこそ、こちらは公開ページです。</p>
    </div>
  </React.StrictMode>
);
  • src/dashboard.jsx(管理画面用):
import React from 'react';
import ReactDOM from 'react-dom/client';
import './dashboard.css';

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <div>
      <h1>ダッシュボード</h1>
      <p>管理画面へようこそ。</p>
    </div>
  </React.StrictMode>
);

3. CSSの分離

  • src/index.css
body {
  font-family: Arial, sans-serif;
  text-align: center;
  background-color: #f0f0f0;
}
h1 {
  color: #282c34;
}
  • src/dashboard.css
body {
  font-family: Arial, sans-serif;
  text-align: center;
  background-color: #e0e0e0;
}
h1 {
  color: #61dafb;
}

開発とビルド

開発モード

npm run dev
  • http://localhost:5173/でランディングページ。
  • http://localhost:5173/dashboard.htmlで管理画面。

ビルド

npm run build

dist/maindashboardの資産が生成。プレビュー:

npm run preview

活用例

  • MPAの構築: 管理画面と公開ページを分離しつつ、共有コンポーネントをsrc/components/で管理。
  • パフォーマンス: 各ページが独立しているため、不要なコードの読み込みを回避。

動作確認

ビルド後、両方のページが正しく表示され、スタイルが適用されているか確認してください。


この記事が役に立ったら、ぜひ「いいね」や「ストック」をお願いします!質問や感想はコメント欄で気軽にどうぞ。Viteの柔軟性を活かして開発を楽しんでください!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?