1
1

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は高速な開発体験を提供するビルドツールですが、静的サイトジェネレーション(SSG)にも活用できます。SSGを使えば、SEOに強く軽量なサイトを簡単に作れます。この記事では、ViteでSSGを実践し、シンプルなサイトを構築します。

SSGとは?

SSG(Static Site Generation)は、ビルド時にHTMLを事前生成する手法です。

  • 利点: 高速な読み込み、SEO対策が容易、サーバー負荷の軽減。
  • Viteの適性: 高速ビルドとシンプルな設定でSSGに最適。

プロジェクトのセットアップ

Reactベースのプロジェクトを用意します。ターミナルで以下を実行:

npm create vite@latest my-ssg-site -- --template react
cd my-ssg-site
npm install

SSG用にプラグインを追加:

npm install vite-plugin-ssg --save-dev

静的ページの生成

1. ルーティングの設定

src/pagesフォルダを作成し、ページを追加:

  • src/pages/Index.jsx:
export default function Index() {
  return (
    <div>
      <h1>ホーム</h1>
      <p>ようこそ!</p>
    </div>
  );
}
  • src/pages/About.jsx:
export default function About() {
  return (
    <div>
      <h1>このサイトについて</h1>
      <p>Viteで作られた静的サイトです。</p>
    </div>
  );
}

2. vite.config.tsの設定

vite.config.tsを更新:

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

export default defineConfig({
  plugins: [
    react(),
    VitePluginSsg({
      routes: ['/', '/about'],
    }),
  ],
});

3. メインエントリーの調整

src/main.jsxを更新:

import React from 'react';
import ReactDOM from 'react-dom/client';
import Index from './pages/Index';
import About from './pages/About';

const routes = {
  '/': Index,
  '/about': About,
};

const App = () => {
  const path = window.location.pathname;
  const Component = routes[path] || Index;
  return <Component />;
};

ReactDOM.createRoot(document.getElementById('root')).render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

ビルドとプレビュー

ビルドを実行:

npm run build

dist/に静的ファイルが生成されます。プレビューで確認:

npm run preview

http://localhost:4173//aboutにアクセスし、ページが表示されるかテスト。

SEO対策の追加

src/pages/Index.jsxにmetaタグを追加:

import { Helmet } from 'react-helmet';

export default function Index() {
  return (
    <div>
      <Helmet>
        <title>ホーム | Vite SSG</title>
        <meta name="description" content="Viteで作った軽量な静的サイト" />
      </Helmet>
      <h1>ホーム</h1>
      <p>ようこそ!</p>
    </div>
  );
}

react-helmetをインストール:

npm install react-helmet

デプロイ

Netlifyにデプロイします:

  1. dist/フォルダをドラッグ&ドロップでアップロード。
  2. または、GitHubリポジトリと連携し、ビルドコマンドをnpm run build、出力ディレクトリをdistに設定。

完成したサイトは、例えばhttps://my-ssg-site.netlify.app/で公開されます。

動作確認

デプロイ後、ホームとAboutページが正しく表示され、SEOタグが反映されているか確認してください。


この記事が役に立ったら、ぜひ「いいね」や「ストック」をお願いします!質問や感想はコメント欄で気軽にどうぞ。Viteで軽量なサイト作りを楽しんでください!

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?