BLOG

ブログ

VitePressとは?基本的な使い方、デプロイ手順を解説します!

ハコザキです。

今回はつい先日1.0(正式版)がリリースされたVitePressについての記事です。
前々から気になっていたものの、なかなか触れずにいたのですが
1.0が出たタイミングで触ってみました。

VitePressとは

JSフレームワークのVueと高速なバンドラである
次世代フロントエンドツールのViteを基盤とした、
Markdown形式で書かれたファイルにテーマを適用し、
静的なHTMLページを生成する静的サイトジェネレーターです。

はじめに | Vue.js
Vite | 次世代フロントエンドツール
静的サイトジェネレーターとは? | Cloudflare

VitePressには、ドキュメントとして利用しやすいデフォルトテーマがあるため、
特に見た目をカスタマイズせずそのまま使えることができます。

また、Vue.jsの公式ドキュメントもVitePressが使用されています。
テーマについては、多言語対応をしているためカスタムテーマを使用しているそうです。
Vue.jsの他にもVite, Vitest, Rollup, D3, Mermaid, VueUse, Pinia, UnoCSSといったドキュメントにもVitePressがすでに使用されています。

使い方

今回は実際にホスティングサービスにデプロイするまでの一連の手順をご紹介します。

各種バージョン情報は以下のとおりです。

  • Node 20.11.0
  • VitePress 1.0.1

VitePress環境の構築

Node.jsバージョンは18以上で、IDEはVSCodeを推奨しています。

まずは、 vitepress-demo というディレクトリを作成し以下のコマンドを実行します。

pnpm add -D vitepress

続いて、以下のコマンドを実行し対話形式でプロジェクトの初期設定を行います。

pnpm vitepress init

今回は以下の回答をしました。

pnpm vitepress init

┌  Welcome to VitePress!
│
◇  Where should VitePress initialize the config?
│  ./docs
│
◇  Site title:
│  My Sample Project
│
◇  Site description:
│  VitePress demo
│
◇  Theme:
│  Default Theme
│
◇  Use TypeScript for config and theme files?
│  Yes
│
◇  Add VitePress npm scripts to package.json?
│  Yes
│
└  Done! Now run pnpm run docs:dev and start writing.

Where should VitePress initialize the config?
-> 初期ファイルの生成場所の指定について、
今回はdocsディレクトリ配下に生成するようにしました。
何も指定しない場合はルート直下に生成されますが、公式サイトでもディレクトリ指定し切り離すように言及しています。
https://vitepress.dev/guide/getting-started#file-structure

Use TypeScript for config and theme files?
-> 今回はTypeScriptを使用したいのでYesにしました。

Add VitePress npm scripts to package.json?
-> Yesでnpm scriptsにコマンドが追加されます。

  "scripts": {
    "docs:dev": "vitepress dev docs",
    "docs:build": "vitepress build docs",
    "docs:preview": "vitepress preview docs"
  }

今回はデフォルトのテーマをそのまま使用します。
続いて、開発用コマンドを実行します。

pnpm run docs:dev

http://localhost:5173 にアクセスし、以下の初期表示ができれば環境構築はokです!

Markdown Examplesリンクをクリックすると以下のような
Vue.jsのドキュメントのようなレイアウトのページが確認できると思います。

ルーティングについて

VitePressはファイルシステムベースのルーティングを採用しています。
このルーティングでは、ディレクトリ構造がそのままパスの構造となります。

ページの新規作成

docs配下 にmdファイルを作成することで、自動でパスが通ります。
docs/introduction.mdを作成します。

# Introduction

hogehoge

この状態で http://localhost:5173/introduction にアクセスすると以下のようにテーマが適用され、
メイン部分に上記のMarkdownの内容が反映されていることが確認できました。

また、docs内にディレクトリを作成することで、
子ページのような形のルーティングをすることも可能です。

# /parent/
docs/parent/index.md

# /parent/child
docs/parent/child.md

ページのリンク

ページ間のリンクには相対パス・絶対パスのどちらでも使用することができます。

Markdown内のリンクの記法については、
通常のMarkdown記法と同様以下のような形でokです。

例として、index.mdとページ追加時に作成したintroduction.mdをリンクしてみます。
それぞれ以下のようにリンクを追加します。

# docs/index.mdに追記
[introduction](./introduction)

# docs/introduction.mdに追記
[Top](./index)

※ 相対パスの場合、以下のようにサジェスト機能が有効になり便利です。

以下のようにページ間でリンクが動作していることを確認できました。

デフォルトテーマ

テーマの設定は docs/.vitepress/config.mts で編集することができます。

初期状態は以下のようになっています。

import { defineConfig } from 'vitepress'

// https://vitepress.dev/reference/site-config
export default defineConfig({
  title: "My Sample Project",
  description: "VitePress demo",
  themeConfig: {
    // https://vitepress.dev/reference/default-theme-config
    nav: [
      { text: 'Home', link: '/' },
      { text: 'Examples', link: '/markdown-examples' }
    ],

    sidebar: [
      {
        text: 'Examples',
        items: [
          { text: 'Markdown Examples', link: '/markdown-examples' },
          { text: 'Runtime API Examples', link: '/api-examples' }
        ]
      }
    ],

    socialLinks: [
      { icon: 'github', link: 'https://github.com/vuejs/vitepress' }
    ]
  }
})

themeConfig内で、ナビゲーションやサイドバーに表示させるコンテンツを表示することができます。

その他にもロゴやフッターなど様々なテーマ内の設定ができます。
詳しくは公式サイトを見てみてください!
Default Theme Config | VitePress

デプロイ

VitePressに限らず、静的サイトジェネレーターでは、
一般的にコマンド実行で静的ファイルを生成し、生成された静的ファイルをホスティングします。

GitHub Pages

今回はGitHub Pagesを使ってデプロイしてみます。

docs/.vitepress/config.mtsに以下を追記します。

import { defineConfig } from "vitepress";

// https://vitepress.dev/reference/site-config
export default defineConfig({

  // 以下追記
  base: "/vitepress-demo/",
});

ローカルでビルドして、本番環境用のプレビューで表示確認をします。

対話形式で環境構築を行った際、
Add VitePress npm scripts to package.json?
でYesを選択した場合は、package.jsonにnpm scriptsが追加されているはずです。

buildコマンドを実行します。

pnpm run docs:build

以下のようにbuild completeと表示されればokです。

pnpm run docs:build

> @ docs:build /Users/hakozaki_k/Desktop/work/hobby/vitepress-demo
> vitepress build docs


  vitepress v1.0.1

✓ building client + server bundles...
✓ rendering pages...
build complete in 1.81s.

distフォルダ内に静的ファイルが出力されています。

distフォルダが出力された後、previewコマンドを実行します。

pnpm run docs:preview

初期状態であれば、http://localhost:4173/ で確認することができます。

.github/workflows/deploy.yml を作成し、以下の記述を行います。
今回はpnpmを使っているので、npmやyarnを使っている場合は適宜変更する必要があります。

# Sample workflow for building and deploying a VitePress site to GitHub Pages
#
name: Deploy VitePress site to Pages

on:
  # Runs on pushes targeting the `main` branch. Change this to `master` if you're
  # using the `master` branch as the default branch.
  push:
    branches: [main]

  # Allows you to run this workflow manually from the Actions tab
  workflow_dispatch:

# Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages
permissions:
  contents: read
  pages: write
  id-token: write

# Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued.
# However, do NOT cancel in-progress runs as we want to allow these production deployments to complete.
concurrency:
  group: pages
  cancel-in-progress: false

jobs:
  # Build job
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout
        uses: actions/checkout@v4
        with:
          fetch-depth: 0 # Not needed if lastUpdated is not enabled
      - uses: pnpm/action-setup@v3
        with:
          version: 8.9.2
      - name: Setup Node
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: pnpm
      - name: Setup Pages
        uses: actions/configure-pages@v4
      - name: Install dependencies
        run: pnpm install
      - name: Build with VitePress
        run: pnpm docs:build
      - name: Upload artifact
        uses: actions/upload-pages-artifact@v3
        with:
          path: docs/.vitepress/dist

  # Deployment job
  deploy:
    environment:
      name: github-pages
      url: ${{ steps.deployment.outputs.page_url }}
    needs: build
    runs-on: ubuntu-latest
    name: Deploy
    steps:
      - name: Deploy to GitHub Pages
        id: deployment
        uses: actions/deploy-pages@v4

続いて、リポジトリにpushする前に.gitignore を作成し以下を記述します。

node_modules/
docs/.vitepress/dist

この状態でGitHubのリポジトリにpushします。

リポジトリにアクセスし、ActionsでCIが動作しているのを確認しましたが、
ビルド失敗していると思います。

リポジトリのSettingsページ、サイドバーのPagesリンクをクリックしGitHub PagesのBuild and deplyment部分にGitHub Actionsを指定する必要があります。

再度jobsを実行することで成功すると思います!!
以下のようなURLでアクセスすると表示できると思います。
https://[username].github.io/[repository]/

まとめ

今回はVitePressの基本的な使い方、デプロイ方法などをご紹介しました。
コンテンツの取得、動的ルート対応などについては本記事では解説していませんが、
実装コストはそこまで高くなく、短時間で実現はできそうです。次の記事でご紹介します!!
Routing | VitePress

会社のコーディングルールや個人用ブログなど、
様々なシーンで利用できると思いますので、ぜひ一度お試しください!!!

RELATED ARTICLE

  • この記事を書いた人
  • 最新の記事