i18n(ja): add japanese guide pages

pull/4969/head
Kenzo-Wada 2 months ago
parent 3d61619ec0
commit 0233972a2f

@ -0,0 +1,225 @@
import { createRequire } from 'module'
import { defineAdditionalConfig, type DefaultTheme } from 'vitepress'
const require = createRequire(import.meta.url)
const pkg = require('vitepress/package.json')
export default defineAdditionalConfig({
description: 'Vite と Vue による静的サイトジェネレーター',
themeConfig: {
nav: nav(),
search: { options: searchOptions() },
sidebar: {
'/ja/guide/': { base: '/ja/guide/', items: sidebarGuide() },
'/ja/reference/': { base: '/ja/reference/', items: sidebarReference() }
},
editLink: {
pattern: 'https://github.com/vuejs/vitepress/edit/main/docs/:path',
text: 'GitHub でこのページを編集'
},
footer: {
message: 'MIT ライセンスの下で公開されています。',
copyright: 'Copyright © 2019-present Evan You'
}
}
})
function nav(): DefaultTheme.NavItem[] {
return [
{
text: 'ガイド',
link: '/ja/guide/what-is-vitepress',
activeMatch: '/guide/'
},
{
text: 'リファレンス',
link: '/ja/reference/site-config',
activeMatch: '/reference/'
},
{
text: pkg.version,
items: [
{
text: '1.6.4',
link: 'https://vuejs.github.io/vitepress/v1/'
},
{
text: '更新履歴',
link: 'https://github.com/vuejs/vitepress/blob/main/CHANGELOG.md'
},
{
text: 'コントリビュート方法',
link: 'https://github.com/vuejs/vitepress/blob/main/.github/contributing.md'
}
]
}
]
}
function sidebarGuide(): DefaultTheme.SidebarItem[] {
return [
{
text: '導入',
collapsed: false,
items: [
{ text: 'VitePress とは?', link: 'what-is-vitepress' },
{ text: 'はじめに', link: 'getting-started' },
{ text: 'ルーティング', link: 'routing' },
{ text: 'デプロイ', link: 'deploy' }
]
},
{
text: '執筆',
collapsed: false,
items: [
{ text: 'Markdown 拡張', link: 'markdown' },
{ text: 'アセットの取り扱い', link: 'asset-handling' },
{ text: 'フロントマター', link: 'frontmatter' },
{ text: 'Markdown で Vue を使う', link: 'using-vue' },
{ text: '多言語対応', link: 'i18n' }
]
},
{
text: 'カスタマイズ',
collapsed: false,
items: [
{ text: 'カスタムテーマを使う', link: 'custom-theme' },
{
text: 'デフォルトテーマの拡張',
link: 'extending-default-theme'
},
{ text: 'ビルド時のデータ読み込み', link: 'data-loading' },
{ text: 'SSR 互換性', link: 'ssr-compat' },
{ text: 'CMS との接続', link: 'cms' }
]
},
{
text: '実験的機能',
collapsed: false,
items: [
{ text: 'MPA モード', link: 'mpa-mode' },
{ text: 'サイトマップ生成', link: 'sitemap-generation' }
]
},
{
text: '設定 & API リファレンス',
base: '/ja/reference/',
link: 'site-config'
}
]
}
function sidebarReference(): DefaultTheme.SidebarItem[] {
return [
{
text: 'リファレンス',
items: [
{ text: 'サイト設定', link: 'site-config' },
{ text: 'Frontmatter 設定', link: 'frontmatter-config' },
{ text: 'ランタイム API', link: 'runtime-api' },
{ text: 'CLI', link: 'cli' },
{
text: 'デフォルトテーマ',
base: '/ja/reference/default-theme-',
items: [
{ text: '概要', link: 'config' },
{ text: 'ナビゲーション', link: 'nav' },
{ text: 'サイドバー', link: 'sidebar' },
{ text: 'ホームページ', link: 'home-page' },
{ text: 'フッター', link: 'footer' },
{ text: 'レイアウト', link: 'layout' },
{ text: 'バッジ', link: 'badge' },
{ text: 'チームページ', link: 'team-page' },
{ text: '前 / 次 リンク', link: 'prev-next-links' },
{ text: '編集リンク', link: 'edit-link' },
{ text: '最終更新日時', link: 'last-updated' },
{ text: '検索', link: 'search' },
{ text: 'Carbon 広告', link: 'carbon-ads' }
]
}
]
}
]
}
function searchOptions(): Partial<DefaultTheme.AlgoliaSearchOptions> {
return {
placeholder: 'ドキュメントを検索',
translations: {
button: {
buttonText: '検索',
buttonAriaLabel: '検索'
},
modal: {
searchBox: {
clearButtonTitle: '検索をクリア',
clearButtonAriaLabel: '検索をクリア',
closeButtonText: '閉じる',
closeButtonAriaLabel: '閉じる',
placeholderText: 'ドキュメントを検索',
placeholderTextAskAi: 'AI に質問: ',
placeholderTextAskAiStreaming: '回答を作成中...',
searchInputLabel: '検索',
backToKeywordSearchButtonText: 'キーワード検索に戻る',
backToKeywordSearchButtonAriaLabel: 'キーワード検索に戻る'
},
startScreen: {
recentSearchesTitle: '検索履歴',
noRecentSearchesText: '最近の検索はありません',
saveRecentSearchButtonTitle: '検索履歴に保存',
removeRecentSearchButtonTitle: '検索履歴から削除',
favoriteSearchesTitle: 'お気に入り',
removeFavoriteSearchButtonTitle: 'お気に入りから削除',
recentConversationsTitle: '最近の会話',
removeRecentConversationButtonTitle: '会話履歴から削除'
},
errorScreen: {
titleText: '結果を取得できません',
helpText: 'ネットワーク接続を確認してください'
},
noResultsScreen: {
noResultsText: '結果が見つかりません',
suggestedQueryText: '別の検索語を試してください',
reportMissingResultsText: '結果があるはずだと思いますか?',
reportMissingResultsLinkText: 'フィードバックを送る'
},
resultsScreen: {
askAiPlaceholder: 'AI に質問: '
},
askAiScreen: {
disclaimerText:
'AI が生成した回答には誤りが含まれる可能性があります。必ずご確認ください。',
relatedSourcesText: '関連ソース',
thinkingText: '考え中...',
copyButtonText: 'コピー',
copyButtonCopiedText: 'コピーしました!',
copyButtonTitle: 'コピー',
likeButtonTitle: 'いいね',
dislikeButtonTitle: 'よくない',
thanksForFeedbackText: 'フィードバックありがとうございます!',
preToolCallText: '検索中...',
duringToolCallText: '検索中 ',
afterToolCallText: '検索完了',
aggregatedToolCallText: '検索完了'
},
footer: {
selectText: '選択',
submitQuestionText: '質問を送信',
selectKeyAriaLabel: 'Enter キー',
navigateText: '移動',
navigateUpKeyAriaLabel: '上矢印キー',
navigateDownKeyAriaLabel: '下矢印キー',
closeText: '閉じる',
backToSearchText: '検索に戻る',
closeKeyAriaLabel: 'Esc キー',
poweredByText: '提供: '
}
}
}
}
}

@ -0,0 +1,66 @@
# アセットの取り扱い
## 静的アセットの参照
すべての Markdown ファイルは Vue コンポーネントにコンパイルされ、[Vite](https://vitejs.dev/guide/assets.html) によって処理されます。Markdown 内では、相対 URL を使ってアセットを参照することが **推奨されます**。
```md
![画像](./image.png)
```
Markdown ファイル内、テーマの `*.vue` コンポーネント内、スタイルや通常の `.css` ファイル内でも、アセットはプロジェクトルートを基準とした絶対パス、またはファイルシステムを基準とした相対パスで参照できます。後者は Vite、Vue CLI、あるいは webpack の `file-loader` を使ったことがある場合に慣れ親しんだ挙動です。
一般的な画像、メディア、フォントファイルタイプは自動的にアセットとして検出され、含まれます。
::: tip リンクされたファイルはアセットとして扱われません
Markdown ファイル内のリンクで参照された PDF やその他のドキュメントは、自動的にアセットとして扱われません。これらのリンクファイルにアクセスできるようにするには、手動でプロジェクトの [`public`](#the-public-directory) ディレクトリに配置する必要があります。
:::
絶対パスを含むすべての参照されたアセットは、プロダクションビルド時にハッシュ化されたファイル名で出力ディレクトリにコピーされます。参照されないアセットはコピーされません。4kb 未満の画像アセットは base64 としてインライン化されます(これは [`vite`](../reference/site-config#vite) 設定オプションで変更可能です)。
すべての **静的な** パス参照(絶対パスを含む)は、作業ディレクトリの構造を基準にする必要があります。
## Public ディレクトリ
Markdown やテーマコンポーネントで直接参照されない静的アセットを提供する必要がある場合や、特定のファイルをオリジナルのファイル名のまま提供したい場合があります。
例えば `robots.txt`、favicon、PWA 用アイコンなどです。
これらのファイルは [ソースディレクトリ](./routing#source-directory) 配下の `public` ディレクトリに配置できます。たとえばプロジェクトルートが `./docs` で、デフォルトのソースディレクトリを使用している場合、`public` ディレクトリは `./docs/public` になります。
`public` に配置されたアセットは、出力ディレクトリのルートにそのままコピーされます。
なお、`public` 内のファイルはルート絶対パスで参照する必要があります。例えば `public/icon.png` は常に `/icon.png` として参照しなければなりません。
## ベース URL
サイトをルート以外の URL にデプロイする場合、`.vitepress/config.js` で `base` オプションを設定する必要があります。
例えば `https://foo.github.io/bar/` にデプロイする場合、`base` は `'/bar/'` と設定します(必ずスラッシュで開始・終了する必要があります)。
すべての静的アセットパスは `base` 設定値に応じて自動的に調整されます。
例えば Markdown 内で `public` 配下のアセットを絶対参照した場合:
```md
![画像](/image-inside-public.png)
```
この場合は `base` の設定値を変更しても、参照を修正する必要はありません。
ただし、テーマコンポーネントで動的にアセットをリンクする場合(例:テーマ設定値に基づいた画像の `src`)は注意が必要です。
```vue
<img :src="theme.logoPath" />
```
この場合は、VitePress が提供する [`withBase` ヘルパー](../reference/runtime-api#withbase) でパスをラップすることを推奨します。
```vue
<script setup>
import { withBase, useData } from 'vitepress'
const { theme } = useData()
</script>
<template>
<img :src="withBase(theme.logoPath)" />
</template>
```

@ -0,0 +1,56 @@
---
outline: deep
---
# CMS との接続
## 全体のワークフロー
VitePress を CMS と接続する際は、主に [動的ルーティング](./routing#dynamic-routes) を中心に考えることになります。先にその仕組みを理解しておいてください。
CMS ごとに動作が異なるため、ここでは各自の環境に合わせて調整できる汎用的なワークフローのみを示します。
1. CMS が認証を必要とする場合は、API トークンを格納するための `.env` を作成し、次のように読み込みます。
```js
// posts/[id].paths.js
import { loadEnv } from 'vitepress'
const env = loadEnv('', process.cwd())
```
2. CMS から必要なデータを取得し、適切なパスデータの形式に整形します。
```js
export default {
async paths() {
// 必要に応じて各 CMS のクライアントライブラリを使用
const data = await (await fetch('https://my-cms-api', {
headers: {
// 必要ならトークン
}
})).json()
return data.map(entry => {
return {
params: { id: entry.id, /* title, authors, date など */ },
content: entry.content
}
})
}
}
```
3. ページ内でコンテンツをレンダリングします。
```md
# {{ $params.title }}
- {{ $params.date }} に {{ $params.author }} が作成
<!-- @content -->
```
## 連携ガイドの募集
特定の CMS と VitePress の連携ガイドを書かれた方は、下部の「Edit this page」リンクからぜひ投稿してください

@ -0,0 +1,212 @@
# カスタムテーマを使う
## テーマの解決
カスタムテーマを有効にするには、`.vitepress/theme/index.js` または `.vitepress/theme/index.ts` ファイル(「テーマエントリファイル」)を作成します。
```
.
├─ docs # プロジェクトルート
│ ├─ .vitepress
│ │ ├─ theme
│ │ │ └─ index.js # テーマエントリ
│ │ └─ config.js # 設定ファイル
│ └─ index.md
└─ package.json
```
VitePress はテーマエントリファイルを検出すると、常にデフォルトテーマではなくカスタムテーマを使用します。ただし、[デフォルトテーマを拡張](./extending-default-theme) してその上で高度なカスタマイズを行うことも可能です。
## テーマインターフェース
VitePress のカスタムテーマは次のインターフェースを持つオブジェクトとして定義されます。
```ts
interface Theme {
/**
* すべてのページに適用されるルートレイアウトコンポーネント
* @required
*/
Layout: Component
/**
* Vue アプリインスタンスを拡張
* @optional
*/
enhanceApp?: (ctx: EnhanceAppContext) => Awaitable<void>
/**
* 別のテーマを拡張し、そのテーマの `enhanceApp` を先に実行
* @optional
*/
extends?: Theme
}
interface EnhanceAppContext {
app: App // Vue アプリインスタンス
router: Router // VitePress のルーターインスタンス
siteData: Ref<SiteData> // サイト全体のメタデータ
}
```
テーマエントリファイルでは、このテーマをデフォルトエクスポートとして公開します。
```js [.vitepress/theme/index.js]
// テーマエントリでは Vue ファイルを直接インポートできます
// VitePress は @vitejs/plugin-vue をあらかじめ設定済みです
import Layout from './Layout.vue'
export default {
Layout,
enhanceApp({ app, router, siteData }) {
// ...
}
}
```
デフォルトエクスポートはカスタムテーマにおける唯一の契約であり、必須なのは `Layout` プロパティだけです。つまり、VitePress のテーマは単一の Vue コンポーネントでも成り立ちます。
レイアウトコンポーネントの内部は通常の Vite + Vue 3 アプリケーションと同じように動作します。なお、テーマは [SSR 対応](./ssr-compat) である必要があります。
## レイアウトの構築
最も基本的なレイアウトコンポーネントには [`<Content />`](../reference/runtime-api#content) コンポーネントを含める必要があります。
```vue [.vitepress/theme/Layout.vue]
<template>
<h1>Custom Layout!</h1>
<!-- この部分に markdown コンテンツが描画されます -->
<Content />
</template>
```
上記のレイアウトは、すべてのページの Markdown を単純に HTML として描画します。最初の改善点として 404 エラー処理を追加できます。
```vue{1-4,9-12}
<script setup>
import { useData } from 'vitepress'
const { page } = useData()
</script>
<template>
<h1>Custom Layout!</h1>
<div v-if="page.isNotFound">
Custom 404 page!
</div>
<Content v-else />
</template>
```
[`useData()`](../reference/runtime-api#usedata) ヘルパーを使うと、条件によってレイアウトを切り替えるために必要なすべてのランタイムデータを取得できます。アクセスできるデータのひとつにフロントマターがあります。これを利用すると、ページごとにレイアウトを制御できます。例えば、ユーザーが特別なホームページレイアウトを使いたい場合は以下のように記述します。
```md
---
layout: home
---
```
テーマ側を次のように調整します。
```vue{3,12-14}
<script setup>
import { useData } from 'vitepress'
const { page, frontmatter } = useData()
</script>
<template>
<h1>Custom Layout!</h1>
<div v-if="page.isNotFound">
Custom 404 page!
</div>
<div v-if="frontmatter.layout === 'home'">
Custom home page!
</div>
<Content v-else />
</template>
```
もちろんレイアウトをさらにコンポーネントに分割することもできます。
```vue{3-5,12-15}
<script setup>
import { useData } from 'vitepress'
import NotFound from './NotFound.vue'
import Home from './Home.vue'
import Page from './Page.vue'
const { page, frontmatter } = useData()
</script>
<template>
<h1>Custom Layout!</h1>
<NotFound v-if="page.isNotFound" />
<Home v-if="frontmatter.layout === 'home'" />
<Page v-else /> <!-- <Page /> が <Content /> を描画 -->
</template>
```
利用可能なすべての機能は [Runtime API リファレンス](../reference/runtime-api) を参照してください。さらに [ビルド時データ読み込み](./data-loading) を活用すれば、ブログ記事一覧ページのようなデータ駆動型のレイアウトも実現できます。
## カスタムテーマの配布
最も簡単な配布方法は [GitHub のテンプレートリポジトリ](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-template-repository) として提供することです。
npm パッケージとして配布する場合は、次の手順を踏みます。
1. パッケージエントリでテーマオブジェクトをデフォルトエクスポートとして公開する。
2. 必要であればテーマ設定の型定義を `ThemeConfig` として公開する。
3. テーマが VitePress 設定の調整を必要とする場合は、パッケージのサブパス(例:`my-theme/config`)としてその設定を公開し、ユーザーが拡張できるようにする。
4. 設定ファイルやフロントマターを通じて、テーマ設定オプションを文書化する。
5. テーマの利用方法を明確に説明する(以下を参照)。
## カスタムテーマの利用
外部テーマを利用するには、カスタムテーマエントリからインポートして再エクスポートします。
```js [.vitepress/theme/index.js]
import Theme from 'awesome-vitepress-theme'
export default Theme
```
テーマを拡張する必要がある場合:
```js [.vitepress/theme/index.js]
import Theme from 'awesome-vitepress-theme'
export default {
extends: Theme,
enhanceApp(ctx) {
// ...
}
}
```
テーマが特別な VitePress 設定を必要とする場合は、設定ファイルも拡張する必要があります。
```ts [.vitepress/config.ts]
import baseConfig from 'awesome-vitepress-theme/config'
export default {
// 必要に応じてテーマの基本設定を拡張
extends: baseConfig
}
```
テーマがテーマ設定用の型を提供している場合:
```ts [.vitepress/config.ts]
import baseConfig from 'awesome-vitepress-theme/config'
import { defineConfigWithTheme } from 'vitepress'
import type { ThemeConfig } from 'awesome-vitepress-theme'
export default defineConfigWithTheme<ThemeConfig>({
extends: baseConfig,
themeConfig: {
// 型は `ThemeConfig`
}
})
```

@ -0,0 +1,210 @@
# ビルド時のデータの読み込み
VitePress には **データローダー (data loaders)** という機能があり、任意のデータを読み込み、ページやコンポーネントからインポートすることができます。データの読み込みは **ビルド時のみ** 実行され、最終的な JavaScript バンドルには JSON としてシリアライズされたデータが含まれます。
データローダーはリモートデータの取得や、ローカルファイルに基づいたメタデータの生成に利用できます。たとえば、ローカルの API ページをすべて解析して API エントリのインデックスを自動生成するといったことが可能です。
## 基本的な使い方
データローダーファイルは `.data.js` または `.data.ts` で終わる必要があります。ファイルは `load()` メソッドを持つオブジェクトをデフォルトエクスポートします。
```js [example.data.js]
export default {
load() {
return {
hello: 'world'
}
}
}
```
ローダーモジュールは Node.js 上でのみ評価されるため、Node API や npm 依存関係を自由に利用できます。
その後、このファイルから `.md` ページや `.vue` コンポーネントで `data` という名前のエクスポートを使ってデータをインポートできます。
```vue
<script setup>
import { data } from './example.data.js'
</script>
<pre>{{ data }}</pre>
```
出力:
```json
{
"hello": "world"
}
```
データローダー自体は `data` を直接エクスポートしていないことに気づくでしょう。これは VitePress が裏側で `load()` を呼び出し、その結果を暗黙的に `data` として公開しているためです。
ローダーが非同期でも動作します。
```js
export default {
async load() {
// リモートデータを取得
return (await fetch('...')).json()
}
}
```
## ローカルファイルからのデータ
ローカルファイルに基づいたデータを生成する必要がある場合は、データローダー内で `watch` オプションを使用し、ファイルの変更をホットリロードに反映させることが推奨されます。
`watch` では [glob パターン](https://github.com/mrmlnc/fast-glob#pattern-syntax) を利用して複数ファイルをマッチさせることができ、パターンはローダーファイルからの相対パスで指定できます。`load()` 関数にはマッチしたファイルの絶対パスが渡されます。
以下は CSV ファイルを読み込み [csv-parse](https://github.com/adaltas/node-csv/tree/master/packages/csv-parse/) を使って JSON に変換する例です。このコードはビルド時にのみ実行されるため、CSV パーサーがクライアントに送られることはありません。
```js
import fs from 'node:fs'
import { parse } from 'csv-parse/sync'
export default {
watch: ['./data/*.csv'],
load(watchedFiles) {
return watchedFiles.map((file) => {
return parse(fs.readFileSync(file, 'utf-8'), {
columns: true,
skip_empty_lines: true
})
})
}
}
```
## `createContentLoader`
コンテンツ中心のサイトを構築する場合、ブログ記事や API ページなどを一覧表示する「アーカイブ」や「インデックス」ページが必要になることがよくあります。これはデータローダー API を使って直接実装できますが、あまりにも一般的なケースなので VitePress では `createContentLoader` というヘルパーが用意されています。
```js [posts.data.js]
import { createContentLoader } from 'vitepress'
export default createContentLoader('posts/*.md', /* options */)
```
このヘルパーは [ソースディレクトリ](./routing#source-directory) からの相対 glob パターンを受け取り、`{ watch, load }` を返すデータローダーオブジェクトを生成します。これをデータローダーファイルのデフォルトエクスポートにできます。開発時のパフォーマンスを向上させるために、ファイルの更新時刻に基づくキャッシュも行われます。
このローダーは Markdown ファイルにのみ対応し、それ以外のファイルは無視されます。
読み込まれるデータは `ContentData[]` 型の配列です。
```ts
interface ContentData {
url: string // ページのマッピング URL例: /posts/hello.html
frontmatter: Record<string, any> // ページのフロントマター
src: string | undefined
html: string | undefined
excerpt: string | undefined
}
```
デフォルトでは `url``frontmatter` のみが提供されます。これは読み込まれたデータがクライアントバンドルに JSON としてインライン化されるため、サイズに注意する必要があるためです。
以下はデータを使って最小限のブログインデックスページを構築する例です。
```vue
<script setup>
import { data as posts } from './posts.data.js'
</script>
<template>
<h1>All Blog Posts</h1>
<ul>
<li v-for="post of posts">
<a :href="post.url">{{ post.frontmatter.title }}</a>
<span>by {{ post.frontmatter.author }}</span>
</li>
</ul>
</template>
```
### オプション
デフォルトデータが要件に合わない場合は、オプションで変換処理を追加できます。
```js [posts.data.js]
import { createContentLoader } from 'vitepress'
export default createContentLoader('posts/*.md', {
includeSrc: true, // 生の markdown ソースを含める?
render: true, // レンダリングされた HTML を含める?
excerpt: true, // 抜粋を含める?
transform(rawData) {
return rawData
.sort((a, b) => {
return +new Date(b.frontmatter.date) - +new Date(a.frontmatter.date)
})
.map((page) => {
page.src // 生の markdown ソース
page.html // レンダリングされた HTML
page.excerpt // 抜粋 HTML最初の `---` までの内容)
return {/* ... */}
})
}
})
```
[Vue.js ブログ](https://github.com/vuejs/blog/blob/main/.vitepress/theme/posts.data.ts) での使用例も参考になります。
`createContentLoader` API は [ビルドフック](../reference/site-config#build-hooks) 内でも利用可能です。
```js [.vitepress/config.js]
export default {
async buildEnd() {
const posts = await createContentLoader('posts/*.md').load()
// メタデータを基にファイルを生成(例: RSS フィード)
}
}
```
**型定義**
```ts
interface ContentOptions<T = ContentData[]> {
includeSrc?: boolean
render?: boolean
excerpt?:
| boolean
| ((file: { data: { [key: string]: any }; content: string; excerpt?: string }, options?: any) => void)
| string
transform?: (data: ContentData[]) => T | Promise<T>
}
```
## 型付きデータローダー
TypeScript を使用する場合は、ローダーと `data` エクスポートを型付けできます。
```ts
import { defineLoader } from 'vitepress'
export interface Data {
// データ型
}
declare const data: Data
export { data }
export default defineLoader({
watch: ['...'],
async load(): Promise<Data> {
// ...
}
})
```
## 設定情報の取得
ローダー内で設定情報を取得するには次のようにします。
```ts
import type { SiteConfig } from 'vitepress'
const config: SiteConfig = (globalThis as any).VITEPRESS_CONFIG
```

@ -0,0 +1,343 @@
---
outline: deep
---
# VitePress サイトをデプロイする
以下のガイドは、次の前提に基づいています。
- VitePress のサイトはプロジェクトの `docs` ディレクトリ内にある。
- デフォルトのビルド出力ディレクトリ(`.vitepress/dist`)を使用している。
- VitePress はプロジェクトのローカル依存としてインストールされており、`package.json` に次のスクリプトが設定されている。
```json [package.json]
{
"scripts": {
"docs:build": "vitepress build docs",
"docs:preview": "vitepress preview docs"
}
}
```
## ローカルでビルドしてテストする
1. 次のコマンドでドキュメントをビルドします。
```sh
$ npm run docs:build
```
2. ビルド後、次のコマンドでローカルプレビューします。
```sh
$ npm run docs:preview
```
`preview` コマンドはローカルの静的 Web サーバーを起動し、出力ディレクトリ `.vitepress/dist``http://localhost:4173` で配信します。プロダクションへプッシュする前に見た目を確認できます。
3. `--port` 引数でサーバーのポートを設定できます。
```json
{
"scripts": {
"docs:preview": "vitepress preview docs --port 8080"
}
}
```
これで `docs:preview``http://localhost:8080` でサーバーを起動します。
## 公開ベースパスの設定
デフォルトでは、サイトはドメインのルートパス(`/`)にデプロイされることを想定しています。サイトをサブパス、例:`https://mywebsite.com/blog/` で配信する場合は、VitePress の設定で [`base`](../reference/site-config#base) オプションを `'/blog/'` に設定してください。
**例:** GitHubまたは GitLabPages に `user.github.io/repo/` としてデプロイするなら、`base` を `/repo/` に設定します。
## HTTP キャッシュヘッダー
本番サーバーの HTTP ヘッダーを制御できる場合は、`cache-control` ヘッダーを設定して、再訪時のパフォーマンスを向上させましょう。
本番ビルドでは静的アセットJavaScript、CSS、`public` 以外のインポートアセット)にハッシュ付きファイル名が使用されます。ブラウザの開発者ツールのネットワークタブで本番プレビューを確認すると、`app.4f283b18.js` のようなファイルが見られます。
この `4f283b18` ハッシュはファイル内容から生成されます。同じハッシュの URL は同じ内容を必ず返し、内容が変われば URL も変わります。したがって、これらのファイルには最も強いキャッシュヘッダーを安全に適用できます。これらのファイルは出力ディレクトリ内の `assets/` 配下に配置されるため、次のヘッダーを設定できます。
```
Cache-Control: max-age=31536000,immutable
```
::: details Netlify の `_headers` ファイル例
```
/assets/*
cache-control: max-age=31536000
cache-control: immutable
```
注:`_headers` ファイルは [public ディレクトリ](./asset-handling#the-public-directory) に配置します(この例では `docs/public/_headers`)。そうすると、ビルド出力にそのままコピーされます。
[Netlify のカスタムヘッダードキュメント](https://docs.netlify.com/routing/headers/)
:::
::: details `vercel.json` による Vercel 設定例
```json
{
"headers": [
{
"source": "/assets/(.*)",
"headers": [
{
"key": "Cache-Control",
"value": "max-age=31536000, immutable"
}
]
}
]
}
```
注:`vercel.json` は **リポジトリのルート** に配置してください。
[Vercel のヘッダー設定ドキュメント](https://vercel.com/docs/concepts/projects/project-configuration#headers)
:::
## プラットフォーム別ガイド
### Netlify / Vercel / Cloudflare Pages / AWS Amplify / Render
新しいプロジェクトを作成し、ダッシュボードで次の設定に変更します。
- **Build Command:** `npm run docs:build`
- **Output Directory:** `docs/.vitepress/dist`
- **Node Version:** `20`(以上)
::: warning
HTML の _Auto Minify_ のようなオプションを有効にしないでください。Vue にとって意味のあるコメントが出力から削除され、削除されるとハイドレーションの不整合エラーが発生する可能性があります。
:::
### GitHub Pages
1. プロジェクトの `.github/workflows` ディレクトリに `deploy.yml` を作成し、以下の内容を記述します。
```yaml [.github/workflows/deploy.yml]
# 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 # Uncomment this block if you're using pnpm
# with:
# version: 9 # Not needed if you've set "packageManager" in package.json
# - uses: oven-sh/setup-bun@v1 # Uncomment this if you're using Bun
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 22
cache: npm # or pnpm / yarn
- name: Setup Pages
uses: actions/configure-pages@v4
- name: Install dependencies
run: npm ci # or pnpm install / yarn install / bun install
- name: Build with VitePress
run: npm run docs:build # or pnpm docs:build / yarn docs:build / bun run 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
```
::: warning
VitePress の `base` オプションが正しく設定されていることを確認してください。詳細は [公開ベースパスの設定](#公開ベースパスの設定) を参照してください。
:::
2. リポジトリ設定の「Pages」メニューで、「Build and deployment > Source」を「GitHub Actions」に設定します。
3. 変更を `main` ブランチにプッシュし、GitHub Actions の完了を待ちます。設定に応じて、サイトは `https://<username>.github.io/[repository]/` または `https://<custom-domain>/` にデプロイされます。以後、`main` へのプッシュごとに自動デプロイされます。
### GitLab Pages
1. VitePress の設定で `outDir``../public` に設定します。`https://<username>.gitlab.io/<repository>/` にデプロイする場合は `base``'/<repository>/'` に設定します。カスタムドメイン、ユーザー/グループページ、または GitLab の「Use unique domain」を有効にしている場合は `base` は不要です。
2. プロジェクトのルートに `.gitlab-ci.yml` を作成して、以下を追加します。これにより、コンテンツを更新するたびにサイトがビルド・デプロイされます。
```yaml [.gitlab-ci.yml]
image: node:18
pages:
cache:
paths:
- node_modules/
script:
# - apk add git # Uncomment this if you're using small docker images like alpine and have lastUpdated enabled
- npm install
- npm run docs:build
artifacts:
paths:
- public
only:
- main
```
### Azure Static Web Apps
1. [公式ドキュメント](https://docs.microsoft.com/en-us/azure/static-web-apps/build-configuration) に従います。
2. 設定ファイルで次の値を指定します(`api_location` のように不要なものは削除)。
- **`app_location`**: `/`
- **`output_location`**: `docs/.vitepress/dist`
- **`app_build_command`**: `npm run docs:build`
### Firebase
1. プロジェクトのルートに `firebase.json``.firebaserc` を作成します。
`firebase.json`:
```json [firebase.json]
{
"hosting": {
"public": "docs/.vitepress/dist",
"ignore": []
}
}
```
`.firebaserc`:
```json [.firebaserc]
{
"projects": {
"default": "<YOUR_FIREBASE_ID>"
}
}
```
2. `npm run docs:build` の後、次のコマンドでデプロイします。
```sh
firebase deploy
```
### Surge
1. `npm run docs:build` の後、次のコマンドでデプロイします。
```sh
npx surge docs/.vitepress/dist
```
### Heroku
1. [`heroku-buildpack-static`](https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-static) のドキュメントとガイドに従います。
2. プロジェクトのルートに `static.json` を作成し、以下を記述します。
```json [static.json]
{
"root": "docs/.vitepress/dist"
}
```
### Edgio
[Creating and Deploying a VitePress App To Edgio](https://docs.edg.io/guides/vitepress) を参照してください。
### Kinsta Static Site Hosting
[VitePress](https://kinsta.com/static-site-hosting/) を [こちらの手順](https://kinsta.com/docs/vitepress-static-site-example/) に従ってデプロイできます。
### Stormkit
[VitePress プロジェクトを Stormkit にデプロイ](https://stormkit.io/blog/how-to-deploy-vitepress) する手順を参照してください。
### CloudRay
[CloudRay](https://cloudray.io/) でのデプロイ方法は [こちらの手順](https://cloudray.io/articles/how-to-deploy-vitepress-site) を参照してください。
### Nginx
以下は Nginx サーバーブロックの設定例です。一般的なテキスト系アセットの gzip 圧縮、VitePress サイトの静的ファイル配信における適切なキャッシュヘッダー、そして `cleanUrls: true` のハンドリングを含みます。
```nginx
server {
gzip on;
gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript;
listen 80;
server_name _;
index index.html;
location / {
# content location
root /app;
# exact matches -> reverse clean urls -> folders -> not found
try_files $uri $uri.html $uri/ =404;
# non existent pages
error_page 404 /404.html;
# a folder without index.html raises 403 in this setup
error_page 403 /404.html;
# adjust caching headers
# files in the assets folder have hashes filenames
location ~* ^/assets/ {
expires 1y;
add_header Cache-Control "public, immutable";
}
}
}
```
この設定は、ビルド済みの VitePress サイトがサーバー上の `/app` ディレクトリに配置されていることを想定しています。サイトのファイルが別の場所にある場合は、`root` ディレクティブを適宜変更してください。
::: warning index.html をデフォルトにしない
`try_files` の解決先を、他の Vue アプリのように index.html にフォールバックさせないでください。不正なページ状態になります。
:::
詳細は [公式 nginx ドキュメント](https://nginx.org/en/docs/)、Issue [#2837](https://github.com/vuejs/vitepress/discussions/2837)、[#3235](https://github.com/vuejs/vitepress/issues/3235)、および Mehdi Merah 氏の [ブログ記事](https://blog.mehdi.cc/articles/vitepress-cleanurls-on-nginx-environment#readings) を参照してください。

@ -0,0 +1,332 @@
---
outline: deep
---
# デフォルトテーマの拡張
VitePress のデフォルトテーマはドキュメント向けに最適化されており、カスタマイズ可能です。利用できるオプションの一覧は [デフォルトテーマの概要](../reference/default-theme-config) を参照してください。
しかし、設定だけでは不十分なケースもあります。例えば:
1. CSS のスタイルを微調整したい
2. グローバルコンポーネントの登録など、Vue アプリインスタンスを変更したい
3. レイアウトのスロット経由でテーマに独自コンテンツを挿入したい
これらの高度なカスタマイズには、デフォルトテーマを「拡張」するカスタムテーマを使用する必要があります。
::: tip
先に [カスタムテーマの使用](./custom-theme) を読み、カスタムテーマの仕組みを理解してから進めてください。
:::
## CSS のカスタマイズ
デフォルトテーマの CSS は、ルートレベルの CSS 変数をオーバーライドすることでカスタマイズできます。
```js [.vitepress/theme/index.js]
import DefaultTheme from 'vitepress/theme'
import './custom.css'
export default DefaultTheme
```
```css
/* .vitepress/theme/custom.css */
:root {
--vp-c-brand-1: #646cff;
--vp-c-brand-2: #747bff;
}
```
上書き可能な [デフォルトテーマの CSS 変数](https://github.com/vuejs/vitepress/blob/main/src/client/theme-default/styles/vars.css) を参照してください。
## フォントを変更する
VitePress はデフォルトフォントとして [Inter](https://rsms.me/inter/) を使用し、ビルド出力にフォントを含めます。プロダクションでは自動でプリロードもされます。しかし、別のメインフォントを使いたい場合には望ましくないことがあります。
Inter をビルド出力に含めたくない場合は、`vitepress/theme-without-fonts` からテーマをインポートします。
```js [.vitepress/theme/index.js]
import DefaultTheme from 'vitepress/theme-without-fonts'
import './my-fonts.css'
export default DefaultTheme
```
```css
/* .vitepress/theme/my-fonts.css */
:root {
--vp-font-family-base: /* 通常テキスト用フォント */
--vp-font-family-mono: /* コード用フォント */
}
```
::: warning
[Team Page](../reference/default-theme-team-page) などのオプションコンポーネントを使う場合も、必ず `vitepress/theme-without-fonts` からインポートしてください。
:::
フォントが `@font-face` で参照されるローカルファイルの場合、アセットとして処理され、ハッシュ付きファイル名で `.vitepress/dist/assets` に出力されます。このファイルをプリロードするには、[transformHead](../reference/site-config#transformhead) ビルドフックを使います。
```js [.vitepress/config.js]
export default {
transformHead({ assets }) {
// 使うフォントに合わせて正規表現を調整
const myFontFile = assets.find(file => /font-name\.[\w-]+\.woff2/.test(file))
if (myFontFile) {
return [
[
'link',
{
rel: 'preload',
href: myFontFile,
as: 'font',
type: 'font/woff2',
crossorigin: ''
}
]
]
}
}
}
```
## グローバルコンポーネントの登録
```js [.vitepress/theme/index.js]
import DefaultTheme from 'vitepress/theme'
/** @type {import('vitepress').Theme} */
export default {
extends: DefaultTheme,
enhanceApp({ app }) {
// 独自のグローバルコンポーネントを登録
app.component('MyGlobalComponent' /* ... */)
}
}
```
TypeScript を使う場合:
```ts [.vitepress/theme/index.ts]
import type { Theme } from 'vitepress'
import DefaultTheme from 'vitepress/theme'
export default {
extends: DefaultTheme,
enhanceApp({ app }) {
// 独自のグローバルコンポーネントを登録
app.component('MyGlobalComponent' /* ... */)
}
} satisfies Theme
```
Vite を使っているため、Vite の [glob import 機能](https://vitejs.dev/guide/features.html#glob-import) を利用してディレクトリ内のコンポーネントを自動登録することもできます。
## レイアウトスロット
デフォルトテーマの `<Layout/>` コンポーネントには、ページ内の特定の位置にコンテンツを挿入するためのスロットがいくつか用意されています。以下は、アウトラインの前にコンポーネントを挿入する例です。
```js [.vitepress/theme/index.js]
import DefaultTheme from 'vitepress/theme'
import MyLayout from './MyLayout.vue'
export default {
extends: DefaultTheme,
// スロットを注入するラッパーコンポーネントで Layout を上書き
Layout: MyLayout
}
```
```vue [.vitepress/theme/MyLayout.vue]
<script setup>
import DefaultTheme from 'vitepress/theme'
const { Layout } = DefaultTheme
</script>
<template>
<Layout>
<template #aside-outline-before>
My custom sidebar top content
</template>
</Layout>
</template>
```
レンダーファンクションを使う方法もあります。
```js [.vitepress/theme/index.js]
import { h } from 'vue'
import DefaultTheme from 'vitepress/theme'
import MyComponent from './MyComponent.vue'
export default {
extends: DefaultTheme,
Layout() {
return h(DefaultTheme.Layout, null, {
'aside-outline-before': () => h(MyComponent)
})
}
}
```
デフォルトテーマレイアウトで利用可能なスロットの一覧:
- フロントマターで `layout: 'doc'`(デフォルト)を有効にしているとき:
- `doc-top`
- `doc-bottom`
- `doc-footer-before`
- `doc-before`
- `doc-after`
- `sidebar-nav-before`
- `sidebar-nav-after`
- `aside-top`
- `aside-bottom`
- `aside-outline-before`
- `aside-outline-after`
- `aside-ads-before`
- `aside-ads-after`
- フロントマターで `layout: 'home'` を有効にしているとき:
- `home-hero-before`
- `home-hero-info-before`
- `home-hero-info`
- `home-hero-info-after`
- `home-hero-actions-after`
- `home-hero-image`
- `home-hero-after`
- `home-features-before`
- `home-features-after`
- フロントマターで `layout: 'page'` を有効にしているとき:
- `page-top`
- `page-bottom`
- 404Not Foundページ:
- `not-found`
- 常に利用可能:
- `layout-top`
- `layout-bottom`
- `nav-bar-title-before`
- `nav-bar-title-after`
- `nav-bar-content-before`
- `nav-bar-content-after`
- `nav-screen-content-before`
- `nav-screen-content-after`
## View Transitions API の利用
### 外観切り替え時(ライト/ダーク)
カラーモード切り替え時にカスタムトランジションを提供するよう、デフォルトテーマを拡張できます。例:
```vue [.vitepress/theme/Layout.vue]
<script setup lang="ts">
import { useData } from 'vitepress'
import DefaultTheme from 'vitepress/theme'
import { nextTick, provide } from 'vue'
const { isDark } = useData()
const enableTransitions = () =>
'startViewTransition' in document &&
window.matchMedia('(prefers-reduced-motion: no-preference)').matches
provide('toggle-appearance', async ({ clientX: x, clientY: y }: MouseEvent) => {
if (!enableTransitions()) {
isDark.value = !isDark.value
return
}
const clipPath = [
`circle(0px at ${x}px ${y}px)`,
`circle(${Math.hypot(
Math.max(x, innerWidth - x),
Math.max(y, innerHeight - y)
)}px at ${x}px ${y}px)`
]
await document.startViewTransition(async () => {
isDark.value = !isDark.value
await nextTick()
}).ready
document.documentElement.animate(
{ clipPath: isDark.value ? clipPath.reverse() : clipPath },
{
duration: 300,
easing: 'ease-in',
fill: 'forwards',
pseudoElement: `::view-transition-${isDark.value ? 'old' : 'new'}(root)`
}
)
})
</script>
<template>
<DefaultTheme.Layout />
</template>
<style>
::view-transition-old(root),
::view-transition-new(root) {
animation: none;
mix-blend-mode: normal;
}
::view-transition-old(root),
.dark::view-transition-new(root) {
z-index: 1;
}
::view-transition-new(root),
.dark::view-transition-old(root) {
z-index: 9999;
}
.VPSwitchAppearance {
width: 22px !important;
}
.VPSwitchAppearance .check {
transform: none !important;
}
</style>
```
結果(**注意!**:点滅や急な動き、明るい光を含みます):
<details>
<summary>デモ</summary>
![Appearance Toggle Transition Demo](/appearance-toggle-transition.webp)
</details>
詳細は [Chrome Docs](https://developer.chrome.com/docs/web-platform/view-transitions/) を参照してください。
### ルート遷移時
近日公開。
## 内部コンポーネントの置き換え
Vite の [エイリアス](https://vitejs.dev/config/shared-options.html#resolve-alias) を使って、デフォルトテーマのコンポーネントを独自のものに置き換えられます。
```ts
import { fileURLToPath, URL } from 'node:url'
import { defineConfig } from 'vitepress'
export default defineConfig({
vite: {
resolve: {
alias: [
{
find: /^.*\/VPNavBar\.vue$/,
replacement: fileURLToPath(
new URL('./theme/components/CustomNavBar.vue', import.meta.url)
)
}
]
}
}
})
```
正確なコンポーネント名は [ソースコード](https://github.com/vuejs/vitepress/tree/main/src/client/theme-default/components) を参照してください。内部コンポーネントであるため、マイナーリリース間で名称が更新される可能性があります。

@ -0,0 +1,48 @@
# フロントマター
## 使い方
VitePress はすべての Markdown ファイルで YAML フロントマターをサポートしており、[gray-matter](https://github.com/jonschlinkert/gray-matter) で解析します。フロントマターは Markdown ファイルの先頭(`<script>` タグを含むあらゆる要素より前)に配置し、三本のハイフンで囲まれた **有効な YAML** 形式で記述します。例:
```md
---
title: Docs with VitePress
editLink: true
---
```
サイトやデフォルトテーマの多くの設定オプションには、フロントマター上で対応するオプションがあります。フロントマターを使うことで、**そのページに限って** 特定の振る舞いを上書きできます。詳細は [Frontmatter Config Reference](../reference/frontmatter-config) を参照してください。
また、独自のカスタムフロントマターデータを定義し、ページ上の動的な Vue 式で利用することもできます。
## フロントマターデータへのアクセス
フロントマターデータは特別なグローバル変数 `$frontmatter` で参照できます。
Markdown ファイル内での使用例:
```md
---
title: Docs with VitePress
editLink: true
---
# {{ $frontmatter.title }}
Guide content
```
[`useData()`](../reference/runtime-api#usedata) ヘルパーを使えば、`<script setup>` 内からも現在のページのフロントマターデータにアクセスできます。
## 代替フロントマター形式
VitePress は JSON フロントマター構文もサポートしています。中括弧で開始・終了する形式です。
```json
---
{
"title": "Blogging Like a Hacker",
"editLink": true
}
---
```

@ -0,0 +1,197 @@
# はじめに
## オンラインで試す
[VitePress](https://vitepress.new) をブラウザ上で直接試すことができます。
## インストール
### 前提条件
- [Node.js](https://nodejs.org/) バージョン 18 以上
- VitePress をコマンドラインインターフェース (CLI) で操作するためのターミナル
- [Markdown](https://en.wikipedia.org/wiki/Markdown) 構文に対応したテキストエディタ
- 推奨: [VSCode](https://code.visualstudio.com/) と [公式 Vue 拡張](https://marketplace.visualstudio.com/items?itemName=Vue.volar)
VitePress は単独でも利用できますし、既存プロジェクトに組み込むことも可能です。いずれの場合も以下でインストールできます。
::: code-group
```sh [npm]
$ npm add -D vitepress@next
```
```sh [pnpm]
$ pnpm add -D vitepress@next
```
```sh [yarn]
$ yarn add -D vitepress@next vue
```
```sh [bun]
$ bun add -D vitepress@next
```
:::
::: tip 注意
VitePress は ESM 専用パッケージです。`require()` を使ってインポートせず、最も近い `package.json``"type": "module"` を含めるか、`.vitepress/config.js` を `.mjs` / `.mts` に変更してください。詳しくは [Vite のトラブルシューティングガイド](http://vitejs.dev/guide/troubleshooting.html#this-package-is-esm-only) を参照してください。また、非同期 CJS コンテキスト内では `await import('vitepress')` を使用できます。
:::
### セットアップウィザード
VitePress にはコマンドラインのセットアップウィザードが付属しており、基本的なプロジェクトを簡単に作成できます。インストール後、以下のコマンドでウィザードを起動します。
::: code-group
```sh [npm]
$ npx vitepress init
```
```sh [pnpm]
$ pnpm vitepress init
```
```sh [yarn]
$ yarn vitepress init
```
```sh [bun]
$ bun vitepress init
```
:::
いくつかの簡単な質問が表示されます。
<<< @/snippets/init.ansi
::: tip Vue をピア依存関係に
Vue コンポーネントや API を使ったカスタマイズを行う場合は、明示的に `vue` を依存関係としてインストールしてください。
:::
## ファイル構成
スタンドアロンの VitePress サイトを構築する場合は、現在のディレクトリ (`./`) にサイトを作成できます。しかし、既存プロジェクトに VitePress を追加する場合は、他のソースコードと分離するために `./docs` などのサブディレクトリに作成することをおすすめします。
例えば `./docs` に VitePress プロジェクトを作成した場合、生成されるファイル構成は以下のようになります。
```
.
├─ docs
│ ├─ .vitepress
│ │ └─ config.js
│ ├─ api-examples.md
│ ├─ markdown-examples.md
│ └─ index.md
└─ package.json
```
`docs` ディレクトリが VitePress サイトの **プロジェクトルート** とみなされます。`.vitepress` ディレクトリは VitePress の設定ファイル、開発サーバーのキャッシュ、ビルド出力、テーマのカスタマイズコードなどに予約されています。
::: tip
デフォルトでは開発サーバーのキャッシュは `.vitepress/cache` に、本番ビルド出力は `.vitepress/dist` に保存されます。Git を使用している場合は `.gitignore` に追加してください。これらの場所は [設定](../reference/site-config#outdir) で変更可能です。
:::
### 設定ファイル
設定ファイル (`.vitepress/config.js`) では、VitePress サイトのさまざまな動作をカスタマイズできます。最も基本的なオプションはサイトのタイトルと説明です。
```js [.vitepress/config.js]
export default {
// サイトレベルのオプション
title: 'VitePress',
description: 'Just playing around.',
themeConfig: {
// テーマレベルのオプション
}
}
```
テーマの動作は `themeConfig` オプションで設定できます。利用可能なすべての設定オプションは [Config Reference](../reference/site-config) を参照してください。
### ソースファイル
`.vitepress` ディレクトリ外の Markdown ファイルは **ソースファイル** とみなされます。
VitePress は **ファイルベースのルーティング** を採用しています。各 `.md` ファイルは同じパスを持つ `.html` ファイルにコンパイルされます。例えば `index.md``index.html` にコンパイルされ、サイトのルート `/` で表示されます。
VitePress にはクリーン URL の生成、パスの書き換え、動的なページ生成といった機能もあります。これらは [ルーティングガイド](./routing) で解説します。
## 実行してみる
セットアッププロセスで許可した場合、以下の npm スクリプトが `package.json` に追加されています。
```json [package.json]
{
...
"scripts": {
"docs:dev": "vitepress dev docs",
"docs:build": "vitepress build docs",
"docs:preview": "vitepress preview docs"
},
...
}
```
`docs:dev` スクリプトを実行すると、即時ホットリロード対応のローカル開発サーバーが起動します。次のコマンドで実行します。
::: code-group
```sh [npm]
$ npm run docs:dev
```
```sh [pnpm]
$ pnpm run docs:dev
```
```sh [yarn]
$ yarn docs:dev
```
```sh [bun]
$ bun run docs:dev
```
:::
npm スクリプトではなく、直接 VitePress を実行することもできます。
::: code-group
```sh [npm]
$ npx vitepress dev docs
```
```sh [pnpm]
$ pnpm vitepress dev docs
```
```sh [yarn]
$ yarn vitepress dev docs
```
```sh [bun]
$ bun vitepress dev docs
```
:::
その他のコマンドラインの使い方は [CLI リファレンス](../reference/cli) に記載されています。
開発サーバーは `http://localhost:5173` で動作します。ブラウザでこの URL にアクセスすると、新しいサイトが確認できます。
## 次のステップ
- Markdown ファイルがどのように HTML にマッピングされるかを理解するには、[ルーティングガイド](./routing) を読みましょう。
- ページ内でできることMarkdown コンテンツの記述や Vue コンポーネントの利用などを知るには、ガイドの「Writing」セクションを参照してください。まずは [Markdown 拡張](./markdown) を学ぶのがおすすめです。
- デフォルトドキュメントテーマの機能を知りたい場合は、[Default Theme Config Reference](../reference/default-theme-config) を確認してください。
- サイトの見た目をさらにカスタマイズしたい場合は、[デフォルトテーマの拡張](./extending-default-theme) や [カスタムテーマの構築](./custom-theme) を検討してください。
- ドキュメントサイトが形になったら、必ず [デプロイガイド](./deploy) を読んでください。

@ -0,0 +1,111 @@
# 多言語対応
組み込みの i18n 機能を使うには、次のようなディレクトリ構成を作成します。
```
docs/
├─ es/
│ ├─ foo.md
├─ fr/
│ ├─ foo.md
├─ foo.md
```
次に `docs/.vitepress/config.ts` で設定します。
```ts [docs/.vitepress/config.ts]
import { defineConfig } from 'vitepress'
export default defineConfig({
// 共有のプロパティやトップレベル設定...
locales: {
root: {
label: 'English',
lang: 'en'
},
fr: {
label: 'French',
lang: 'fr', // 省略可。最終的に html タグの `lang` 属性として付与されます
link: '/fr/guide' // デフォルトは /fr/。ナビバーの言語メニューに表示。外部 URL でも可
// ロケール固有のその他のプロパティ...
}
}
})
```
各ロケールroot を含む)ごとに、次のプロパティを上書きできます。
```ts
interface LocaleSpecificConfig<ThemeConfig = any> {
lang?: string
dir?: string
title?: string
titleTemplate?: string | boolean
description?: string
head?: HeadConfig[] // 既存の head とマージ。重複する meta タグは自動的に除去
themeConfig?: ThemeConfig // シャローにマージ。共通項目はトップレベルの themeConfig に置けます
}
```
デフォルトテーマのプレースホルダ文言のカスタマイズについては [`DefaultTheme.Config`](https://github.com/vuejs/vitepress/blob/main/types/default-theme.d.ts) を参照してください。`themeConfig.algolia` や `themeConfig.carbonAds` をロケール単位で上書きしないでください。多言語検索の利用は [Algolia ドキュメント](../reference/default-theme-search#i18n) を参照。
**プロ向けヒント:** 設定ファイルは `docs/.vitepress/config/index.ts` に置くこともできます。ロケールごとに設定ファイルを作成して、`index.ts` でマージ・エクスポートすると整理しやすくなります。
## ロケールごとにディレクトリを分ける
次のような構成でも問題ありません。
```
docs/
├─ en/
│ ├─ foo.md
├─ es/
│ ├─ foo.md
├─ fr/
├─ foo.md
```
ただし、VitePress はデフォルトで `/` から `/en/` へのリダイレクトを行いません。これにはサーバー側の設定が必要です。たとえば Netlify では、`docs/public/_redirects` に次のようなファイルを追加できます。
```
/* /es/:splat 302 Language=es
/* /fr/:splat 302 Language=fr
/* /en/:splat 302
```
**プロ向けヒント:** 上記の方法を使う場合、`nf_lang` クッキーでユーザーの言語選択を保持できます。
```ts [docs/.vitepress/theme/index.ts]
import DefaultTheme from 'vitepress/theme'
import Layout from './Layout.vue'
export default {
extends: DefaultTheme,
Layout
}
```
```vue [docs/.vitepress/theme/Layout.vue]
<script setup lang="ts">
import DefaultTheme from 'vitepress/theme'
import { useData, inBrowser } from 'vitepress'
import { watchEffect } from 'vue'
const { lang } = useData()
watchEffect(() => {
if (inBrowser) {
document.cookie = `nf_lang=${lang.value}; expires=Mon, 1 Jan 2030 00:00:00 UTC; path=/`
}
})
</script>
<template>
<DefaultTheme.Layout />
</template>
```
## RTL サポート(実験的)
RTL をサポートするには、設定で `dir: 'rtl'` を指定し、<https://github.com/MohammadYounes/rtlcss><https://github.com/vkalinichev/postcss-rtl>、または <https://github.com/elchininet/postcss-rtlcss> のような RTLCSS 系の PostCSS プラグインを使用してください。CSS の詳細度の問題を避けるため、PostCSS プラグインでは `:where([dir="ltr"])``:where([dir="rtl"])` を接頭辞として使うよう設定してください。

File diff suppressed because it is too large Load Diff

@ -0,0 +1,23 @@
# VitePress 0.x からの移行
VitePress 0.x をお使いの場合、新機能や強化に伴ういくつかの破壊的変更があります。ここでは最新の VitePress へアプリを移行する際の手順を説明します。
## アプリ設定
- 国際化機能i18nはまだ実装されていません。
## テーマ設定
- `sidebar` オプションの構造が変わりました。
- `children` キーは `items` に名称変更されました。
- ルート直下の項目に現在は `link` を含められません。将来的に再導入予定です。
- `repo`, `repoLabel`, `docsDir`, `docsBranch`, `editLinks`, `editLinkText` は、より柔軟な API に置き換えられて削除されました。
- ナビゲーションにアイコン付きの GitHub リンクを追加するには、[ソーシャルリンク](../reference/default-theme-nav#navigation-links) を使用してください。
- 「このページを編集」リンクを追加するには、[編集リンク](../reference/default-theme-edit-link) を使用してください。
- `lastUpdated` オプションは `config.lastUpdated``themeConfig.lastUpdatedText` に分割されました。
- `carbonAds.carbon``carbonAds.code` に変更されました。
## フロントマター設定
- `home: true``layout: home` に変更されました。あわせてホームページ関連の設定が拡張され、多くが変更されています。詳細は [ホームページのガイド](../reference/default-theme-home-page) を参照してください。
- `footer` オプションは [`themeConfig.footer`](../reference/default-theme-config#footer) に移動しました。

@ -0,0 +1,33 @@
# VuePress からの移行
## 設定
### サイドバー
サイドバーはフロントマターから自動生成されなくなりました。サイドバーを動的に生成するには、[自分でフロントマターを読み取り](https://github.com/vuejs/vitepress/issues/572#issuecomment-1170116225)、項目を構築してください。将来的に、[この用途のユーティリティ](https://github.com/vuejs/vitepress/issues/96) が提供される可能性があります。
## Markdown
### 画像
VuePress と異なり、VitePress では静的画像を使用する場合、設定の [`base`](./asset-handling#base-url) を自動的に処理します。
そのため、`img` タグを使わずに画像をレンダリングできます。
```diff
- <img :src="$withBase('/foo.png')" alt="foo">
+ ![foo](/foo.png)
```
::: warning
動的な画像については、[ベース URL のガイド](./asset-handling#base-url) にあるとおり、引き続き `withBase` が必要です。
:::
すべての `img` タグを `![](...)` 構文へ置換するには、次の正規表現を使って `![$2]($1)` に置き換えてください。
- 検索:`<img.*withBase\('(.*)'\).*alt="([^"]*)".*>`
- 置換:`![$2]($1)`
---
続きは今後追加予定です…

@ -0,0 +1,23 @@
# MPA モード <Badge type="warning" text="experimental" />
MPAMulti-Page Applicationモードは、コマンドラインの `vitepress build --mpa`、または設定で `mpa: true` を指定することで有効化できます。
MPA モードでは、既定で **あらゆるページが JavaScript を含まずに** レンダリングされます。結果として、本番サイトは監査ツールにおける初回訪問のパフォーマンススコアが向上しやすくなります。
一方、SPA のナビゲーションがないため、ページ間リンクはフルリロードになります。読み込み後のページ遷移は、SPA モードのような即時性はありません。
また、「既定で JS なし」ということは、実質的に Vue をサーバーサイドのテンプレート言語としてのみ使うことを意味します。ブラウザ側ではイベントハンドラがアタッチされないため、インタラクティブ性はありません。クライアントサイドの JavaScript を読み込むには、特別な `<script client>` タグを使用します:
```html
<script client>
document.querySelector('h1').addEventListener('click', () => {
console.log('client side JavaScript!')
})
</script>
# Hello
```
`<script client>` は VitePress 固有の機能であり、Vue の機能ではありません。`.md` と `.vue` の両方で動作しますが、**MPA モード時のみ** 有効です。テーマコンポーネント内のクライアントスクリプトはひとつにバンドルされ、特定ページ専用のクライアントスクリプトはそのページごとに分割されます。
なお、`<script client>` は **Vue コンポーネントのコードとしては評価されません**。プレーンな JavaScript モジュールとして処理されます。このため、MPA モードはクライアント側のインタラクションを極力最小限に抑えたいサイトにのみ使用するのが適しています。

@ -0,0 +1,385 @@
---
outline: deep
---
# ルーティング
## ファイルベースのルーティング
VitePress はファイルベースのルーティングを採用しており、生成される HTML はソースの Markdown ファイルのディレクトリ構造に対応します。例えば、次のディレクトリ構造があるとします:
```
.
├─ guide
│ ├─ getting-started.md
│ └─ index.md
├─ index.md
└─ prologue.md
```
生成される HTML は次のとおりです:
```
index.md --> /index.html / でアクセス可能)
prologue.md --> /prologue.html
guide/index.md --> /guide/index.html /guide/ でアクセス可能)
guide/getting-started.md --> /guide/getting-started.html
```
生成された HTML は、静的ファイルを配信できる任意の Web サーバーでホストできます。
## ルートディレクトリとソースディレクトリ
VitePress プロジェクトのファイル構成には重要な概念が 2 つあります:**プロジェクトルート** と **ソースディレクトリ** です。
### プロジェクトルート
プロジェクトルートは、VitePress が特別なディレクトリである `.vitepress` を探しにいく場所です。`.vitepress` ディレクトリは、VitePress の設定ファイル、開発サーバーのキャッシュ、ビルド出力、任意のテーマカスタマイズコードのための予約場所です。
コマンドラインから `vitepress dev``vitepress build` を実行すると、VitePress は現在の作業ディレクトリをプロジェクトルートとして使用します。サブディレクトリをルートとして指定したい場合は、コマンドに相対パスを渡します。例えば、VitePress プロジェクトが `./docs` にある場合、`vitepress dev docs` を実行します:
```
.
├─ docs # プロジェクトルート
│ ├─ .vitepress # 設定ディレクトリ
│ ├─ getting-started.md
│ └─ index.md
└─ ...
```
```sh
vitepress dev docs
```
これにより、ソースから HTML へのマッピングは次のようになります:
```
docs/index.md --> /index.html / でアクセス可能)
docs/getting-started.md --> /getting-started.html
```
### ソースディレクトリ
ソースディレクトリは、Markdown のソースファイルを置く場所です。既定ではプロジェクトルートと同じです。ただし、[`srcDir`](../reference/site-config#srcdir) 設定オプションで変更できます。
`srcDir` はプロジェクトルートからの相対パスで解決されます。例えば `srcDir: 'src'` の場合、ファイル構成は次のようになります:
```
. # プロジェクトルート
├─ .vitepress # 設定ディレクトリ
└─ src # ソースディレクトリ
├─ getting-started.md
└─ index.md
```
ソースから HTML へのマッピングは次のとおりです:
```
src/index.md --> /index.html / でアクセス可能)
src/getting-started.md --> /getting-started.html
```
## ページ間リンク
ページ間のリンクには、絶対パスと相対パスのどちらも使用できます。`.md` と `.html` の拡張子はどちらも機能しますが、最終的な URL を設定に応じて VitePress が生成できるよう、**拡張子は省略する** のがベストプラクティスです。
```md
<!-- 良い例 -->
[はじめに](./getting-started)
[はじめに](../guide/getting-started)
<!-- 悪い例 -->
[はじめに](./getting-started.md)
[はじめに](./getting-started.html)
```
画像などのアセットへのリンクについては、[アセットの取り扱い](./asset-handling) を参照してください。
### VitePress 管理外のページへのリンク
サイト内で VitePress が生成していないページへリンクしたい場合は、フル URL新しいタブで開くを使うか、明示的にターゲットを指定します。
**入力**
```md
[pure.html へのリンク](/pure.html){target="_self"}
```
**出力**
[pure.html へのリンク](/pure.html){target="_self"}
::: tip 注意
Markdown のリンクでは、`base` が自動的に URL の先頭に付与されます。つまり、`base` の外にあるページへリンクしたい場合は、ブラウザの相対解決に従って `../../pure.html` のように書く必要があります。
あるいは、アンカータグの構文を直接使うこともできます:
```md
<a href="/pure.html" target="_self">pure.html へのリンク</a>
```
:::
## クリーン URL の生成
::: warning サーバー側の対応が必要
VitePress でクリーン URL を提供するには、サーバー側のサポートが必要です。
:::
既定では、VitePress は内部リンクを `.html` で終わる URL に解決します。しかし、`.html` を含まない「クリーン URL」`example.com/path`)を好む場合もあります。
一部のサーバーやホスティングNetlify、Vercel、GitHub Pagesは、リダイレクトなしに `/foo``/foo.html` にマッピングできます。
- Netlify と GitHub Pages はデフォルトで対応しています。
- Vercel は [`vercel.json` の `cleanUrls` オプション](https://vercel.com/docs/concepts/projects/project-configuration#cleanurls) を有効にする必要があります。
この機能が利用可能であれば、VitePress 側の [`cleanUrls`](../reference/site-config#cleanurls) 設定も有効化してください。これにより:
- ページ間の内部リンクが `.html` 拡張子なしで生成されます。
- 現在のパスが `.html` で終わっている場合、拡張子なしのパスへクライアントサイドのリダイレクトを行います。
もしサーバーをそのように設定できない場合は、次のようなディレクトリ構造に手動でする必要があります:
```
.
├─ getting-started
│ └─ index.md
├─ installation
│ └─ index.md
└─ index.md
```
## ルートのリライトRoute Rewrites
ソースディレクトリ構造と生成ページのマッピングをカスタマイズできます。これは複雑なプロジェクト構成で有用です。例えば、複数パッケージを持つモノレポで、ソースファイルと並べてドキュメントを配置したい場合:
```
.
└─ packages
├─ pkg-a
│ └─ src
│ ├─ foo.md
│ └─ index.md
└─ pkg-b
└─ src
├─ bar.md
└─ index.md
```
生成したいページが次のような場合:
```
packages/pkg-a/src/index.md --> /pkg-a/index.html
packages/pkg-a/src/foo.md --> /pkg-a/foo.html
packages/pkg-b/src/index.md --> /pkg-b/index.html
packages/pkg-b/src/bar.md --> /pkg-b/bar.html
```
[`rewrites`](../reference/site-config#rewrites) オプションを次のように設定します:
```ts [.vitepress/config.js]
export default {
rewrites: {
'packages/pkg-a/src/index.md': 'pkg-a/index.md',
'packages/pkg-a/src/foo.md': 'pkg-a/foo.md',
'packages/pkg-b/src/index.md': 'pkg-b/index.md',
'packages/pkg-b/src/bar.md': 'pkg-b/bar.md'
}
}
```
`rewrites` は動的なルートパラメータにも対応しています。上記の例で多くのパッケージがある場合、同じ構造なら次のように簡略化できます:
```ts
export default {
rewrites: {
'packages/:pkg/src/:slug*': ':pkg/:slug*'
}
}
```
リライトのパスは `path-to-regexp` パッケージでコンパイルされます。高度な構文は[ドキュメント](https://github.com/pillarjs/path-to-regexp/tree/6.x#parameters)を参照してください。
`rewrites` は、元のパスを受け取って新しいパスを返す **関数** として定義することもできます:
```ts
export default {
rewrites(id) {
return id.replace(/^packages\/([^/]+)\/src\//, '$1/')
}
}
```
::: warning リライト時の相対リンク
リライトを有効にした場合、**相対リンクはリライト後のパスに基づいて** 記述してください。例えば、`packages/pkg-a/src/pkg-a-code.md` から `packages/pkg-b/src/pkg-b-code.md` への相対リンクを作るには、次のように書きます:
```md
[PKG B へのリンク](../pkg-b/pkg-b-code)
```
:::
## 動的ルートDynamic Routes
ひとつの Markdown ファイルと動的データから多数のページを生成できます。例えば、`packages/[pkg].md` を作成して、プロジェクト内の各パッケージに対応するページを生成できます。ここで `[pkg]` セグメントは、それぞれのページを区別する **ルートパラメータ** です。
### パスローダーファイル
VitePress は静的サイトジェネレーターなので、生成可能なページパスはビルド時に確定している必要があります。したがって、動的ルートページには **パスローダーファイル** が **必須** です。`packages/[pkg].md` に対しては `packages/[pkg].paths.js``.ts` も可)が必要です:
```
.
└─ packages
├─ [pkg].md # ルートテンプレート
└─ [pkg].paths.js # ルートのパスローダー
```
パスローダーは、`paths` メソッドを持つオブジェクトをデフォルトエクスポートします。`paths` は `params` プロパティを持つオブジェクトの配列を返します。各オブジェクトが 1 ページに対応します。
例えば次の `paths` 配列を返すと:
```js
// packages/[pkg].paths.js
export default {
paths() {
return [
{ params: { pkg: 'foo' }},
{ params: { pkg: 'bar' }}
]
}
}
```
生成される HTML は次のようになります:
```
.
└─ packages
├─ foo.html
└─ bar.html
```
### 複数パラメータ
動的ルートに複数のパラメータを含めることもできます。
**ファイル構成**
```
.
└─ packages
├─ [pkg]-[version].md
└─ [pkg]-[version].paths.js
```
**パスローダー**
```js
export default {
paths: () => [
{ params: { pkg: 'foo', version: '1.0.0' }},
{ params: { pkg: 'foo', version: '2.0.0' }},
{ params: { pkg: 'bar', version: '1.0.0' }},
{ params: { pkg: 'bar', version: '2.0.0' }}
]
}
```
**出力**
```
.
└─ packages
├─ foo-1.0.0.html
├─ foo-2.0.0.html
├─ bar-1.0.0.html
└─ bar-2.0.0.html
```
### パスを動的に生成する
パスローダーモジュールは Node.js 上で実行され、ビルド時にのみ評価されます。ローカルまたはリモートの任意のデータから、動的に配列を生成できます。
ローカルファイルから生成する例:
```js
import fs from 'fs'
export default {
paths() {
return fs
.readdirSync('packages')
.map((pkg) => {
return { params: { pkg } }
})
}
}
```
リモートデータから生成する例:
```js
export default {
async paths() {
const pkgs = await (await fetch('https://my-api.com/packages')).json()
return pkgs.map((pkg) => {
return {
params: {
pkg: pkg.name,
version: pkg.version
}
}
})
}
}
```
### ページ内でパラメータにアクセスする
各ページへ追加データを渡すために、パラメータを利用できます。Markdown のルートファイルでは、Vue 式内で `$params` グローバルプロパティから現在ページのパラメータにアクセスできます:
```md
- パッケージ名: {{ $params.pkg }}
- バージョン: {{ $params.version }}
```
[`useData`](../reference/runtime-api#usedata) ランタイム API からも、現在ページのパラメータにアクセスできますMarkdown と Vue コンポーネントの両方で利用可能):
```vue
<script setup>
import { useData } from 'vitepress'
// params は Vue の ref
const { params } = useData()
console.log(params.value)
</script>
```
### 生コンテンツのレンダリング
ページに渡したパラメータはクライアント JavaScript のペイロードにシリアライズされます。そのため、リモート CMS から取得した生の Markdown や HTML など、重いデータをパラメータに含めるのは避けてください。
代わりに、各パスオブジェクトの `content` プロパティでコンテンツを渡せます:
```js
export default {
async paths() {
const posts = await (await fetch('https://my-cms.com/blog-posts')).json()
return posts.map((post) => {
return {
params: { id: post.id },
content: post.content // 生の Markdown または HTML
}
})
}
}
```
そのうえで、Markdown ファイル内で次の特別な構文を使って、そのコンテンツを埋め込みます:
```md
<!-- @content -->
```

@ -0,0 +1,58 @@
# サイトマップ生成
VitePress には、サイト用の `sitemap.xml` を生成する機能が標準で用意されています。有効化するには、`.vitepress/config.js` に次を追加します。
```ts
export default {
sitemap: {
hostname: 'https://example.com'
}
}
```
`siteamp.xml``<lastmod>` タグを含めるには、[`lastUpdated`](../reference/default-theme-last-updated) オプションを有効にします。
## オプション
サイトマップ生成は [`sitemap`](https://www.npmjs.com/package/sitemap) モジュールで行われます。設定ファイルの `sitemap` に、このモジュールがサポートする任意のオプションを渡せます。指定した値はそのまま `SitemapStream` コンストラクタに渡されます。詳しくは [`sitemap` のドキュメント](https://www.npmjs.com/package/sitemap#options-you-can-pass) を参照してください。例:
```ts
export default {
sitemap: {
hostname: 'https://example.com',
lastmodDateOnly: false
}
}
```
設定で `base` を使っている場合は、`hostname` にもそれを付与してください:
```ts
export default {
base: '/my-site/',
sitemap: {
hostname: 'https://example.com/my-site/'
}
}
```
## `transformItems` フック
`siteamp.xml` に書き出す直前にサイトマップ項目を加工するには、`sitemap.transformItems` フックを使います。このフックはサイトマップ項目の配列を受け取り、配列を返す必要があります。例:
```ts
export default {
sitemap: {
hostname: 'https://example.com',
transformItems: (items) => {
// 既存項目の追加・変更・フィルタリングが可能
items.push({
url: '/extra-page',
changefreq: 'monthly',
priority: 0.8
})
return items
}
}
}
```

@ -0,0 +1,135 @@
---
outline: deep
---
# SSR 互換性
VitePress は本番ビルド時に、Node.js 上で Vue のサーバーサイドレンダリングSSR機能を使ってアプリを事前レンダリングします。つまり、テーマコンポーネント内のすべてのカスタムコードは SSR 互換性の対象になります。
[公式 Vue ドキュメントの SSR セクション](https://vuejs.org/guide/scaling-up/ssr.html)では、SSR とは何か、SSR と SSG の関係、そして SSR に優しいコードを書く際の一般的な注意点が解説されています。経験則としては、**ブラウザ / DOM API へのアクセスは Vue コンポーネントの `beforeMount` または `mounted` フック内に限定** するのが安全です。
## `<ClientOnly>`
SSR に適さないコンポーネント(例:カスタムディレクティブを含むなど)を使用・デモする場合は、組み込みの `<ClientOnly>` コンポーネントでラップできます。
```md
<ClientOnly>
<NonSSRFriendlyComponent />
</ClientOnly>
```
## インポート時に Browser API にアクセスするライブラリ
一部のコンポーネントやライブラリは **インポート時に** ブラウザ API にアクセスします。インポート時にブラウザ環境を前提とするコードを使うには、動的インポートが必要です。
### mounted フック内でのインポート
```vue
<script setup>
import { onMounted } from 'vue'
onMounted(() => {
import('./lib-that-access-window-on-import').then((module) => {
// ここでコードを利用
})
})
</script>
```
### 条件付きインポート
[`import.meta.env.SSR`](https://vitejs.dev/guide/env-and-mode.html#env-variables) フラグVite の環境変数の一部)を使って、依存関係を条件付きでインポートすることもできます。
```js
if (!import.meta.env.SSR) {
import('./lib-that-access-window-on-import').then((module) => {
// ここでコードを利用
})
}
```
[`Theme.enhanceApp`](./custom-theme#theme-interface) は非同期にできるため、**インポート時に Browser API に触れる Vue プラグイン** を条件付きでインポート・登録できます。
```js [.vitepress/theme/index.js]
/** @type {import('vitepress').Theme} */
export default {
// ...
async enhanceApp({ app }) {
if (!import.meta.env.SSR) {
const plugin = await import('plugin-that-access-window-on-import')
app.use(plugin.default)
}
}
}
```
TypeScript を使う場合:
```ts [.vitepress/theme/index.ts]
import type { Theme } from 'vitepress'
export default {
// ...
async enhanceApp({ app }) {
if (!import.meta.env.SSR) {
const plugin = await import('plugin-that-access-window-on-import')
app.use(plugin.default)
}
}
} satisfies Theme
```
### `defineClientComponent`
VitePress は、**インポート時に Browser API にアクセスする Vue コンポーネント** を読み込むためのユーティリティを提供します。
```vue
<script setup>
import { defineClientComponent } from 'vitepress'
const ClientComp = defineClientComponent(() => {
return import('component-that-access-window-on-import')
})
</script>
<template>
<ClientComp />
</template>
```
ターゲットコンポーネントに props / children / slots を渡すこともできます。
```vue
<script setup>
import { ref } from 'vue'
import { defineClientComponent } from 'vitepress'
const clientCompRef = ref(null)
const ClientComp = defineClientComponent(
() => import('component-that-access-window-on-import'),
// 引数は h() に渡されます - https://vuejs.org/api/render-function.html#h
[
{
ref: clientCompRef
},
{
default: () => 'default slot',
foo: () => h('div', 'foo'),
bar: () => [h('span', 'one'), h('span', 'two')]
}
],
// コンポーネント読み込み後のコールバック(非同期可)
() => {
console.log(clientCompRef.value)
}
)
</script>
<template>
<ClientComp />
</template>
```
ターゲットコンポーネントは、ラッパーコンポーネントの mounted フックで初めてインポートされます。

@ -0,0 +1,288 @@
# Markdown で Vue を使う
VitePress では、各 Markdown ファイルはまず HTML にコンパイルされ、その後 [Vue の単一ファイルコンポーネントSFC](https://vuejs.org/guide/scaling-up/sfc.html) として処理されます。つまり、Markdown 内で Vue のあらゆる機能が使えます。動的テンプレート、Vue コンポーネントの利用、`<script>` タグを追加してページ内ロジックを書くことも可能です。
なお、VitePress は Vue のコンパイラを利用して、Markdown コンテンツの**純粋に静的な部分**を自動検出・最適化します。静的コンテンツは単一のプレースホルダノードに最適化され、初回訪問時の JavaScript ペイロードから除外されます。クライアント側のハイドレーションでもスキップされます。要するに、そのページで**動的な部分に対してだけ**コストを支払うことになります。
::: tip SSR 互換性
Vue の使用は SSR 互換である必要があります。詳細と一般的な回避策は [SSR 互換性](./ssr-compat) を参照してください。
:::
## テンプレート記法
### 補間Interpolation
各 Markdown は最初に HTML にコンパイルされ、その後 Vite の処理パイプラインで Vue コンポーネントとして扱われます。つまり、テキスト内で Vue 風の補間が使えます。
**入力**
```md
{{ 1 + 1 }}
```
**出力**
<div class="language-text"><pre><code>{{ 1 + 1 }}</code></pre></div>
### ディレクティブDirectives
ディレクティブも動作します(設計上、生の HTML は Markdown でも有効です)。
**入力**
```html
<span v-for="i in 3">{{ i }}</span>
```
**出力**
<div class="language-text"><pre><code><span v-for="i in 3">{{ i }} </span></code></pre></div>
## `<script>``<style>`
Markdown ファイルのルート直下に置く `<script>``<style>` タグは、Vue の SFC と同様に動作します(`<script setup>` や `<style module>` などを含む)。大きな違いは `<template>` タグが無い点で、その他のルート直下のコンテンツは Markdown になることです。すべてのタグはフロントマターの**後**に配置してください。
```html
---
hello: world
---
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>
## Markdown コンテンツ
現在の値: {{ count }}
<button :class="$style.button" @click="count++">Increment</button>
<style module>
.button {
color: red;
font-weight: bold;
}
</style>
```
::: warning Markdown での `<style scoped>` は避ける
Markdown で `<style scoped>` を使うと、そのページ内のすべての要素に特殊な属性を付与する必要があり、ページサイズが大きく膨らみます。ページ単位でローカルスコープが必要な場合は `<style module>` を推奨します。
:::
VitePress のランタイム API現在ページのメタデータにアクセスできる [`useData` ヘルパー](../reference/runtime-api#usedata))も利用できます。
**入力**
```html
<script setup>
import { useData } from 'vitepress'
const { page } = useData()
</script>
<pre>{{ page }}</pre>
```
**出力**
```json
{
"path": "/using-vue.html",
"title": "Using Vue in Markdown",
"frontmatter": {},
...
}
```
## コンポーネントの利用
Markdown ファイルで、Vue コンポーネントを直接インポートして使用できます。
### Markdown 内でのインポート
特定のページでしか使わないコンポーネントは、そのページで明示的にインポートするのがおすすめです。これにより適切にコード分割され、該当ページでのみ読み込まれます。
```md
<script setup>
import CustomComponent from '../components/CustomComponent.vue'
</script>
# ドキュメント
これはカスタムコンポーネントを使う .md です
<CustomComponent />
## 続き
...
```
### グローバル登録
ほとんどのページで使うコンポーネントは、Vue アプリインスタンスをカスタマイズしてグローバル登録できます。例は [デフォルトテーマの拡張](./extending-default-theme#registering-global-components) を参照してください。
::: warning 重要
カスタムコンポーネント名にはハイフンを含めるか、PascalCase を使用してください。そうでない場合、インライン要素として解釈されて `<p>` タグ内にラップされ、ブロック要素が入れられないためハイドレーション不整合を引き起こします。
:::
### 見出し内でのコンポーネント利用 <ComponentInHeader />
見出し内で Vue コンポーネントを使うこともできますが、次の書き方の違いに注意してください。
| Markdown | 出力 HTML | 解析される見出し |
| ------------------------------------------------------- | ------------------------------------------- | --------------- |
| <pre v-pre><code> # text &lt;Tag/&gt; </code></pre> | `<h1>text <Tag/></h1>` | `text` |
| <pre v-pre><code> # text \`&lt;Tag/&gt;\` </code></pre> | `<h1>text <code>&lt;Tag/&gt;</code></h1>` | `text <Tag/>` |
`<code>` に包まれた HTML はそのまま表示されます。包まれて**いない** HTML だけが Vue によってパースされます。
::: tip
出力 HTML の生成は [Markdown-it](https://github.com/Markdown-it/Markdown-it) が担当し、見出しの解析は VitePress が担当します(サイドバーやドキュメントタイトルに利用)。
:::
## エスケープ
`v-pre` ディレクティブを付けた `<span>` などでラップすることで、Vue の補間をエスケープできます。
**入力**
```md
This <span v-pre>{{ will be displayed as-is }}</span>
```
**出力**
<div class="escape-demo">
<p>This <span v-pre>{{ will be displayed as-is }}</span></p>
</div>
段落全体を `v-pre` のカスタムコンテナで囲む方法もあります。
```md
::: v-pre
{{ This will be displayed as-is }}
:::
```
**出力**
<div class="escape-demo">
::: v-pre
{{ This will be displayed as-is }}
:::
</div>
## コードブロック内でのアンエスケープ
既定では、フェンス付きコードブロックは自動で `v-pre` が付与され、Vue の構文は処理されません。フェンス内で Vue 風の補間を有効にするには、言語に `-vue` サフィックスを付けます(例:`js-vue`)。
**入力**
````md
```js-vue
Hello {{ 1 + 1 }}
```
````
**出力**
```js-vue
Hello {{ 1 + 1 }}
```
この方法では、一部のトークンが正しくシンタックスハイライトされない場合があります。
## CSS プリプロセッサの利用
VitePress は CSS プリプロセッサ(`.scss`、`.sass`、`.less`、`.styl`、`.stylus`)を[標準サポート](https://vitejs.dev/guide/features.html#css-pre-processors)しています。Vite 固有のプラグインは不要ですが、各プリプロセッサ本体のインストールは必要です。
```
# .scss / .sass
npm install -D sass
# .less
npm install -D less
# .styl / .stylus
npm install -D stylus
```
その後、Markdown やテーマコンポーネントで次のように使えます。
```vue
<style lang="sass">
.title
font-size: 20px
</style>
```
## Teleport の利用
現時点で VitePress は、SSG における Teleport を **body** へのみサポートしています。その他のターゲットへ Teleport したい場合は、組み込みの `<ClientOnly>` でラップするか、[`postRender` フック](../reference/site-config#postrender)で最終ページ HTML の適切な位置に Teleport のマークアップを注入してください。
<ModalDemo />
::: details
<<< @/components/ModalDemo.vue
:::
```md
<ClientOnly>
<Teleport to="#modal">
<div>
// ...
</div>
</Teleport>
</ClientOnly>
```
<script setup>
import ModalDemo from '../../components/ModalDemo.vue'
import ComponentInHeader from '../../components/ComponentInHeader.vue'
</script>
<style>
.escape-demo {
border: 1px solid var(--vp-c-border);
border-radius: 8px;
padding: 0 20px;
}
</style>
## VS Code の IntelliSense サポート
<!-- Based on https://github.com/vuejs/language-tools/pull/4321 -->
Vue は [Vue - Official VS Code plugin](https://marketplace.visualstudio.com/items?itemName=Vue.volar) により、標準で IntelliSense を提供します。ただし `.md` ファイルでも有効にするには、設定ファイルをいくつか調整する必要があります。
1. tsconfig/jsconfig の `include``vueCompilerOptions.vitePressExtensions``.md` パターンを追加します。
::: code-group
```json [tsconfig.json]
{
"include": [
"docs/**/*.ts",
"docs/**/*.vue",
"docs/**/*.md",
],
"vueCompilerOptions": {
"vitePressExtensions": [".md"],
},
}
```
:::
2. VS Code の設定で、`vue.server.includeLanguages` に `markdown` を追加します。
::: code-group
```json [.vscode/settings.json]
{
"vue.server.includeLanguages": ["vue", "markdown"]
}
```
:::

@ -0,0 +1,57 @@
# VitePress とは?
VitePress は、高速でコンテンツ中心の Web サイトを構築するための [静的サイトジェネレーターSSG](https://en.wikipedia.org/wiki/Static_site_generator) です。要するに、VitePress は [Markdown](https://en.wikipedia.org/wiki/Markdown) で書かれたソースコンテンツにテーマを適用し、どこにでも簡単にデプロイできる静的 HTML ページを生成します。
<div class="tip custom-block" style="padding-top: 8px">
まずは試してみたい? [クイックスタート](./getting-started) へどうぞ。
</div>
## ユースケース
- **ドキュメント**
VitePress には技術ドキュメント向けに設計されたデフォルトテーマが同梱されています。今あなたが読んでいるこのページのほか、[Vite](https://vitejs.dev/)、[Rollup](https://rollupjs.org/)、[Pinia](https://pinia.vuejs.org/)、[VueUse](https://vueuse.org/)、[Vitest](https://vitest.dev/)、[D3](https://d3js.org/)、[UnoCSS](https://unocss.dev/)、[Iconify](https://iconify.design/) など、[まだまだたくさん](https://github.com/search?q=/"vitepress":+/+language:json&type=code)のドキュメントサイトで使われています。
[公式の Vue.js ドキュメント](https://vuejs.org/) も VitePress をベースにしています(複数言語で共有されるカスタムテーマを使用)。
- **ブログ/ポートフォリオ/マーケティングサイト**
VitePress は [フルカスタムテーマ](./custom-theme) をサポートし、標準的な Vite + Vue アプリ同様の開発体験を提供します。Vite 上に構築されているため、豊富なエコシステムから Vite プラグインを直接活用できます。さらに、[データの読み込み](./data-loading)(ローカル/リモート)や [ルートの動的生成](./routing#dynamic-routes) のための柔軟な API も提供します。ビルド時にデータが確定できる限り、ほとんど何でも構築できます。
公式の [Vue.js ブログ](https://blog.vuejs.org/) は、ローカルコンテンツに基づいてインデックスページを生成するシンプルなブログです。
## 開発体験DX
VitePress は、Markdown コンテンツを扱う際の優れた開発体験DXを目指しています。
- **[Vite 駆動](https://vitejs.dev/)**:即時サーバー起動、編集はページリロードなしで常に瞬時(<100ms)に反映。
- **[ビルトインの Markdown 拡張](./markdown)**Frontmatter、表、シンタックスハイライト…必要なものはひと通り。特にコードブロック周りの機能が充実しており、高度な技術ドキュメントに最適です。
- **[Vue 拡張 Markdown](./using-vue)**:各 Markdown ページは Vue の [単一ファイルコンポーネントSFC](https://vuejs.org/guide/scaling-up/sfc.html) としても機能します。HTML と 100% 互換な Vue テンプレートを活かし、Vue のテンプレート機能やインポートしたコンポーネントで静的コンテンツにインタラクションを埋め込めます。
## パフォーマンス
多くの従来型 SSG と異なり、VitePress で生成されたサイトは **初回訪問では静的 HTML** を返し、その後のサイト内ナビゲーションは [シングルページアプリケーションSPA](https://en.wikipedia.org/wiki/Single-page_application) として動作します。これはパフォーマンス面で最適なバランスだと考えています。
- **初期ロードが速い**
どのページへの初回訪問でも、静的な事前レンダリング HTML が配信され、高速な読み込みと最適な SEO を実現します。続いて JavaScript バンドルが読み込まれ、ページが Vue の SPA に「ハイドレート」されます。SPA のハイドレーションは遅いという通説に反し、Vue 3 の素のパフォーマンスとコンパイラ最適化により非常に高速です。[PageSpeed Insights](https://pagespeed.web.dev/report?url=https%3A%2F%2Fvitepress.dev%2F) でも、VitePress サイトは低速回線のローエンド端末でもほぼ満点のスコアを達成できます。
- **読み込み後のナビゲーションが速い**
さらに重要なのは、初回ロード**後**の体験が向上することです。サイト内の以降の移動ではフルリロードは発生せず、遷移先のコンテンツを取得して動的に更新します。VitePress はビューポート内のリンクに対してページチャンクを自動プリフェッチするため、ほとんどの場合で遷移は「即時」に感じられます。
- **インタラクションのペナルティなし**
静的 Markdown に埋め込まれた動的な Vue 部分をハイドレートできるよう、各 Markdown ページは Vue コンポーネントとして処理され JavaScript にコンパイルされます。一見非効率に思えますが、Vue コンパイラは静的部分と動的部分を賢く分離し、ハイドレーションのコストとペイロードを最小化します。初回ロードでは静的部分は自動的に JS ペイロードから除外され、ハイドレーションでもスキップされます。
## VuePress はどうなるの?
VitePress は VuePress 1 の精神的後継です。元の VuePress 1 は Vue 2 と webpack をベースとしていました。VitePress は内部に Vue 3 と Vite を採用し、開発体験・本番性能・完成度の高いデフォルトテーマ・より柔軟なカスタマイズ API を提供します。
VitePress と VuePress 1 の API の違いは主にテーマやカスタマイズ周りにあります。VuePress 1 でデフォルトテーマを使っている場合は、比較的容易に移行できます。
2 つの SSG を並行して維持するのは現実的ではないため、Vue チームは長期的に VitePress を推奨 SSG とする方針に集中しています。現在、VuePress 1 は非推奨となり、VuePress 2 は今後の開発・保守を VuePress コミュニティチームに委ねています。

@ -0,0 +1,35 @@
---
layout: home
hero:
name: VitePress
text: Vite & Vue をベースにした静的サイトジェネレーター
tagline: Markdown から美しいドキュメントを数分で
actions:
- theme: brand
text: VitePress とは?
link: /guide/what-is-vitepress
- theme: alt
text: クイックスタート
link: /guide/getting-started
- theme: alt
text: GitHub
link: https://github.com/vuejs/vitepress
image:
src: /vitepress-logo-large.svg
alt: VitePress
features:
- icon: 📝
title: コンテンツに集中
details: Markdown だけで、美しいドキュメントサイトを簡単に作成できます。
- icon: <svg xmlns="http://www.w3.org/2000/svg" width="30" viewBox="0 0 256 256.32"><defs><linearGradient id="a" x1="-.828%" x2="57.636%" y1="7.652%" y2="78.411%"><stop offset="0%" stop-color="#41D1FF"/><stop offset="100%" stop-color="#BD34FE"/></linearGradient><linearGradient id="b" x1="43.376%" x2="50.316%" y1="2.242%" y2="89.03%"><stop offset="0%" stop-color="#FFEA83"/><stop offset="8.333%" stop-color="#FFDD35"/><stop offset="100%" stop-color="#FFA800"/></linearGradient></defs><path fill="url(#a)" d="M255.153 37.938 134.897 252.976c-2.483 4.44-8.862 4.466-11.382.048L.875 37.958c-2.746-4.814 1.371-10.646 6.827-9.67l120.385 21.517a6.537 6.537 0 0 0 2.322-.004l117.867-21.483c5.438-.991 9.574 4.796 6.877 9.62Z"/><path fill="url(#b)" d="M185.432.063 96.44 17.501a3.268 3.268 0 0 0-2.634 3.014l-5.474 92.456a3.268 3.268 0 0 0 3.997 3.378l24.777-5.718c2.318-.535 4.413 1.507 3.936 3.838l-7.361 36.047c-.495 2.426 1.782 4.5 4.151 3.78l15.304-4.649c2.372-.72 4.652 1.36 4.15 3.788l-11.698 56.621c-.732 3.542 3.979 5.473 5.943 2.437l1.313-2.028 72.516-144.72c1.215-2.423-.88-5.186-3.54-4.672l-25.505 4.922c-2.396.462-4.435-1.77-3.759-4.114l16.646-57.705c.677-2.35-1.37-4.583-3.769-4.113Z"/></svg>
title: Vite の開発体験を享受
details: 即時サーバー起動、超高速ホットリロード、そして Vite エコシステムのプラグイン活用。
- icon: <svg xmlns="http://www.w3.org/2000/svg" width="30" viewBox="0 0 256 220.8"><path fill="#41B883" d="M204.8 0H256L128 220.8 0 0h97.92L128 51.2 157.44 0h47.36Z"/><path fill="#41B883" d="m0 0 128 220.8L256 0h-51.2L128 132.48 50.56 0H0Z"/><path fill="#35495E" d="M50.56 0 128 133.12 204.8 0h-47.36L128 51.2 97.92 0H50.56Z"/></svg>
title: Vue でカスタマイズ
details: Markdown 内で直接 Vue 構文やコンポーネントを利用したり、Vue で独自テーマを構築できます。
- icon: 🚀
title: 高速サイトを公開
details: 静的 HTML による高速初期ロードと、クライアントサイドルーティングによる快適なページ遷移。
---

@ -0,0 +1,73 @@
# Command Line Interface
## `vitepress dev`
Start VitePress dev server using designated directory as root. Defaults to current directory. The `dev` command can also be omitted when running in current directory.
### Usage
```sh
# start in current directory, omitting `dev`
vitepress
# start in sub directory
vitepress dev [root]
```
### Options
| Option | Description |
| --------------- | ----------------------------------------------------------------- |
| `--open [path]` | Open browser on startup (`boolean \| string`) |
| `--port <port>` | Specify port (`number`) |
| `--base <path>` | Public base path (default: `/`) (`string`) |
| `--cors` | Enable CORS |
| `--strictPort` | Exit if specified port is already in use (`boolean`) |
| `--force` | Force the optimizer to ignore the cache and re-bundle (`boolean`) |
## `vitepress build`
Build the VitePress site for production.
### Usage
```sh
vitepress build [root]
```
### Options
| Option | Description |
| ------------------------------ | ------------------------------------------------------------------------------------------------------------------- |
| `--mpa` (experimental) | Build in [MPA mode](../guide/mpa-mode) without client-side hydration (`boolean`) |
| `--base <path>` | Public base path (default: `/`) (`string`) |
| `--target <target>` | Transpile target (default: `"modules"`) (`string`) |
| `--outDir <dir>` | Output directory relative to **cwd** (default: `<root>/.vitepress/dist`) (`string`) |
| `--assetsInlineLimit <number>` | Static asset base64 inline threshold in bytes (default: `4096`) (`number`) |
## `vitepress preview`
Locally preview the production build.
### Usage
```sh
vitepress preview [root]
```
### Options
| Option | Description |
| --------------- | ------------------------------------------ |
| `--base <path>` | Public base path (default: `/`) (`string`) |
| `--port <port>` | Specify port (`number`) |
## `vitepress init`
Start the [Setup Wizard](../guide/getting-started#setup-wizard) in current directory.
### Usage
```sh
vitepress init
```

@ -0,0 +1,69 @@
# Badge
The badge lets you add status to your headers. For example, it could be useful to specify the section's type, or supported version.
## Usage
You may use the `Badge` component which is globally available.
```html
### Title <Badge type="info" text="default" />
### Title <Badge type="tip" text="^1.9.0" />
### Title <Badge type="warning" text="beta" />
### Title <Badge type="danger" text="caution" />
```
Code above renders like:
### Title <Badge type="info" text="default" />
### Title <Badge type="tip" text="^1.9.0" />
### Title <Badge type="warning" text="beta" />
### Title <Badge type="danger" text="caution" />
## Custom Children
`<Badge>` accept `children`, which will be displayed in the badge.
```html
### Title <Badge type="info">custom element</Badge>
```
### Title <Badge type="info">custom element</Badge>
## Customize Type Color
You can customize the style of badges by overriding css variables. The following are the default values:
```css
:root {
--vp-badge-info-border: transparent;
--vp-badge-info-text: var(--vp-c-text-2);
--vp-badge-info-bg: var(--vp-c-default-soft);
--vp-badge-tip-border: transparent;
--vp-badge-tip-text: var(--vp-c-brand-1);
--vp-badge-tip-bg: var(--vp-c-brand-soft);
--vp-badge-warning-border: transparent;
--vp-badge-warning-text: var(--vp-c-warning-1);
--vp-badge-warning-bg: var(--vp-c-warning-soft);
--vp-badge-danger-border: transparent;
--vp-badge-danger-text: var(--vp-c-danger-1);
--vp-badge-danger-bg: var(--vp-c-danger-soft);
}
```
## `<Badge>`
`<Badge>` component accepts following props:
```ts
interface Props {
// When `<slot>` is passed, this value gets ignored.
text?: string
// Defaults to `tip`.
type?: 'info' | 'tip' | 'warning' | 'danger'
}
```

@ -0,0 +1,22 @@
# Carbon Ads
VitePress has built in native support for [Carbon Ads](https://www.carbonads.net/). By defining the Carbon Ads credentials in config, VitePress will display ads on the page.
```js
export default {
themeConfig: {
carbonAds: {
code: 'your-carbon-code',
placement: 'your-carbon-placement'
}
}
}
```
These values are used to call carbon CDN script as shown below.
```js
`//cdn.carbonads.com/carbon.js?serve=${code}&placement=${placement}`
```
To learn more about Carbon Ads configuration, please visit [Carbon Ads website](https://www.carbonads.net/).

@ -0,0 +1,494 @@
# Default Theme Config
Theme config lets you customize your theme. You can define theme config via the `themeConfig` option in the config file:
```ts
export default {
lang: 'en-US',
title: 'VitePress',
description: 'Vite & Vue powered static site generator.',
// Theme related configurations.
themeConfig: {
logo: '/logo.svg',
nav: [...],
sidebar: { ... }
}
}
```
**The options documented on this page only apply to the default theme.** Different themes expect different theme config. When using a custom theme, the theme config object will be passed to the theme so the theme can define conditional behavior based on it.
## i18nRouting
- Type: `boolean`
Changing locale to say `zh` will change the URL from `/foo` (or `/en/foo/`) to `/zh/foo`. You can disable this behavior by setting `themeConfig.i18nRouting` to `false`.
## logo
- Type: `ThemeableImage`
Logo file to display in nav bar, right before the site title. Accepts a path string, or an object to set a different logo for light/dark mode.
```ts
export default {
themeConfig: {
logo: '/logo.svg'
}
}
```
```ts
type ThemeableImage =
| string
| { src: string; alt?: string }
| { light: string; dark: string; alt?: string }
```
## siteTitle
- Type: `string | false`
You can customize this item to replace the default site title (`title` in app config) in nav. When set to `false`, title in nav will be disabled. Useful when you have `logo` that already contains the site title text.
```ts
export default {
themeConfig: {
siteTitle: 'Hello World'
}
}
```
## nav
- Type: `NavItem`
The configuration for the nav menu item. More details in [Default Theme: Nav](./default-theme-nav#navigation-links).
```ts
export default {
themeConfig: {
nav: [
{ text: 'Guide', link: '/guide' },
{
text: 'Dropdown Menu',
items: [
{ text: 'Item A', link: '/item-1' },
{ text: 'Item B', link: '/item-2' },
{ text: 'Item C', link: '/item-3' }
]
}
]
}
}
```
```ts
type NavItem = NavItemWithLink | NavItemWithChildren
interface NavItemWithLink {
text: string
link: string | ((payload: PageData) => string)
activeMatch?: string
target?: string
rel?: string
noIcon?: boolean
}
interface NavItemChildren {
text?: string
items: NavItemWithLink[]
}
interface NavItemWithChildren {
text?: string
items: (NavItemChildren | NavItemWithLink)[]
activeMatch?: string
}
```
## sidebar
- Type: `Sidebar`
The configuration for the sidebar menu item. More details in [Default Theme: Sidebar](./default-theme-sidebar).
```ts
export default {
themeConfig: {
sidebar: [
{
text: 'Guide',
items: [
{ text: 'Introduction', link: '/introduction' },
{ text: 'Getting Started', link: '/getting-started' },
...
]
}
]
}
}
```
```ts
export type Sidebar = SidebarItem[] | SidebarMulti
export interface SidebarMulti {
[path: string]: SidebarItem[] | { items: SidebarItem[]; base: string }
}
export type SidebarItem = {
/**
* The text label of the item.
*/
text?: string
/**
* The link of the item.
*/
link?: string
/**
* The children of the item.
*/
items?: SidebarItem[]
/**
* If not specified, group is not collapsible.
*
* If `true`, group is collapsible and collapsed by default
*
* If `false`, group is collapsible but expanded by default
*/
collapsed?: boolean
/**
* Base path for the children items.
*/
base?: string
/**
* Customize text that appears on the footer of previous/next page.
*/
docFooterText?: string
rel?: string
target?: string
}
```
## aside
- Type: `boolean | 'left'`
- Default: `true`
- Can be overridden per page via [frontmatter](./frontmatter-config#aside)
Setting this value to `false` prevents rendering of aside container.\
Setting this value to `true` renders the aside to the right.\
Setting this value to `left` renders the aside to the left.
If you want to disable it for all viewports, you should use `outline: false` instead.
## outline
- Type: `Outline | Outline['level'] | false`
- Level can be overridden per page via [frontmatter](./frontmatter-config#outline)
Setting this value to `false` prevents rendering of outline container. Refer this interface for more details:
```ts
interface Outline {
/**
* The levels of headings to be displayed in the outline.
* Single number means only headings of that level will be displayed.
* If a tuple is passed, the first number is the minimum level and the second number is the maximum level.
* `'deep'` is same as `[2, 6]`, which means all headings from `<h2>` to `<h6>` will be displayed.
*
* @default 2
*/
level?: number | [number, number] | 'deep'
/**
* The title to be displayed on the outline.
*
* @default 'On this page'
*/
label?: string
}
```
## socialLinks
- Type: `SocialLink[]`
You may define this option to show your social account links with icons in nav.
```ts
export default {
themeConfig: {
socialLinks: [
// You can add any icon from simple-icons (https://simpleicons.org/):
{ icon: 'github', link: 'https://github.com/vuejs/vitepress' },
{ icon: 'twitter', link: '...' },
// You can also add custom icons by passing SVG as string:
{
icon: {
svg: '<svg role="img" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><title>Dribbble</title><path d="M12...6.38z"/></svg>'
},
link: '...',
// You can include a custom label for accessibility too (optional but recommended):
ariaLabel: 'cool link'
}
]
}
}
```
```ts
interface SocialLink {
icon: string | { svg: string }
link: string
ariaLabel?: string
}
```
## footer
- Type: `Footer`
- Can be overridden per page via [frontmatter](./frontmatter-config#footer)
Footer configuration. You can add a message or copyright text on the footer, however, it will only be displayed when the page doesn't contain a sidebar. This is due to design concerns.
```ts
export default {
themeConfig: {
footer: {
message: 'Released under the MIT License.',
copyright: 'Copyright © 2019-present Evan You'
}
}
}
```
```ts
export interface Footer {
message?: string
copyright?: string
}
```
## editLink
- Type: `EditLink`
- Can be overridden per page via [frontmatter](./frontmatter-config#editlink)
Edit Link lets you display a link to edit the page on Git management services such as GitHub, or GitLab. See [Default Theme: Edit Link](./default-theme-edit-link) for more details.
```ts
export default {
themeConfig: {
editLink: {
pattern: 'https://github.com/vuejs/vitepress/edit/main/docs/:path',
text: 'Edit this page on GitHub'
}
}
}
```
```ts
export interface EditLink {
pattern: string
text?: string
}
```
## lastUpdated
- Type: `LastUpdatedOptions`
Allows customization for the last updated text and date format.
```ts
export default {
themeConfig: {
lastUpdated: {
text: 'Updated at',
formatOptions: {
dateStyle: 'full',
timeStyle: 'medium'
}
}
}
}
```
```ts
export interface LastUpdatedOptions {
/**
* @default 'Last updated'
*/
text?: string
/**
* @default
* { dateStyle: 'short', timeStyle: 'short' }
*/
formatOptions?: Intl.DateTimeFormatOptions & { forceLocale?: boolean }
}
```
## algolia
- Type: `AlgoliaSearch`
An option to support searching your docs site using [Algolia DocSearch](https://docsearch.algolia.com/docs/what-is-docsearch). Learn more in [Default Theme: Search](./default-theme-search)
```ts
export interface AlgoliaSearchOptions extends DocSearchProps {
locales?: Record<string, Partial<DocSearchProps>>
}
```
View full options [here](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts).
## carbonAds {#carbon-ads}
- Type: `CarbonAdsOptions`
An option to display [Carbon Ads](https://www.carbonads.net/).
```ts
export default {
themeConfig: {
carbonAds: {
code: 'your-carbon-code',
placement: 'your-carbon-placement'
}
}
}
```
```ts
export interface CarbonAdsOptions {
code: string
placement: string
}
```
Learn more in [Default Theme: Carbon Ads](./default-theme-carbon-ads)
## docFooter
- Type: `DocFooter`
Can be used to customize text appearing above previous and next links. Helpful if not writing docs in English. Also can be used to disable prev/next links globally. If you want to selectively enable/disable prev/next links, you can use [frontmatter](./default-theme-prev-next-links).
```ts
export default {
themeConfig: {
docFooter: {
prev: 'Pagina prior',
next: 'Proxima pagina'
}
}
}
```
```ts
export interface DocFooter {
prev?: string | false
next?: string | false
}
```
## darkModeSwitchLabel
- Type: `string`
- Default: `Appearance`
Can be used to customize the dark mode switch label. This label is only displayed in the mobile view.
## lightModeSwitchTitle
- Type: `string`
- Default: `Switch to light theme`
Can be used to customize the light mode switch title that appears on hovering.
## darkModeSwitchTitle
- Type: `string`
- Default: `Switch to dark theme`
Can be used to customize the dark mode switch title that appears on hovering.
## sidebarMenuLabel
- Type: `string`
- Default: `Menu`
Can be used to customize the sidebar menu label. This label is only displayed in the mobile view.
## returnToTopLabel
- Type: `string`
- Default: `Return to top`
Can be used to customize the label of the return to top button. This label is only displayed in the mobile view.
## langMenuLabel
- Type: `string`
- Default: `Change language`
Can be used to customize the aria-label of the language toggle button in navbar. This is only used if you're using [i18n](../guide/i18n).
## skipToContentLabel
- Type: `string`
- Default: `Skip to content`
Can be used to customize the label of the skip to content link. This link is shown when the user is navigating the site using a keyboard.
## externalLinkIcon
- Type: `boolean`
- Default: `false`
Whether to show an external link icon next to external links in markdown.
## `useLayout` <Badge type="info" text="composable" />
Returns layout-related data. The returned object has the following type:
```ts
interface {
isHome: ComputedRef<boolean>
sidebar: Readonly<ShallowRef<DefaultTheme.SidebarItem[]>>
sidebarGroups: ComputedRef<DefaultTheme.SidebarItem[]>
hasSidebar: ComputedRef<boolean>
isSidebarEnabled: ComputedRef<boolean>
hasAside: ComputedRef<boolean>
leftAside: ComputedRef<boolean>
headers: Readonly<ShallowRef<DefaultTheme.OutlineItem[]>>
hasLocalNav: ComputedRef<boolean>
}
```
**Example:**
```vue
<script setup>
import { useLayout } from 'vitepress/theme'
const { hasSidebar } = useLayout()
</script>
<template>
<div v-if="hasSidebar">Only show when sidebar exists</div>
</template>
```

@ -0,0 +1,60 @@
# Edit Link
## Site-Level Config
Edit Link lets you display a link to edit the page on Git management services such as GitHub, or GitLab. To enable it, add `themeConfig.editLink` options to your config.
```js
export default {
themeConfig: {
editLink: {
pattern: 'https://github.com/vuejs/vitepress/edit/main/docs/:path'
}
}
}
```
The `pattern` option defines the URL structure for the link, and `:path` is going to be replaced with the page path.
You can also put a pure function that accepts [`PageData`](./runtime-api#usedata) as the argument and returns the URL string.
```js
export default {
themeConfig: {
editLink: {
pattern: ({ filePath }) => {
if (filePath.startsWith('packages/')) {
return `https://github.com/acme/monorepo/edit/main/${filePath}`
} else {
return `https://github.com/acme/monorepo/edit/main/docs/${filePath}`
}
}
}
}
}
```
It should not have side-effects nor access anything outside of its scope since it will be serialized and executed in the browser.
By default, this will add the link text "Edit this page" at the bottom of the doc page. You may customize this text by defining the `text` option.
```js
export default {
themeConfig: {
editLink: {
pattern: 'https://github.com/vuejs/vitepress/edit/main/docs/:path',
text: 'Edit this page on GitHub'
}
}
}
```
## Frontmatter Config
This can be disabled per-page using the `editLink` option on frontmatter:
```yaml
---
editLink: false
---
```

@ -0,0 +1,53 @@
# Footer
VitePress will display global footer at the bottom of the page when `themeConfig.footer` is present.
```ts
export default {
themeConfig: {
footer: {
message: 'Released under the MIT License.',
copyright: 'Copyright © 2019-present Evan You'
}
}
}
```
```ts
export interface Footer {
// The message shown right before copyright.
message?: string
// The actual copyright text.
copyright?: string
}
```
The above configuration also supports HTML strings. So, for example, if you want to configure footer text to have some links, you can adjust the configuration as follows:
```ts
export default {
themeConfig: {
footer: {
message: 'Released under the <a href="https://github.com/vuejs/vitepress/blob/main/LICENSE">MIT License</a>.',
copyright: 'Copyright © 2019-present <a href="https://github.com/yyx990803">Evan You</a>'
}
}
}
```
::: warning
Only inline elements can be used in `message` and `copyright` as they are rendered inside a `<p>` element. If you want to add block elements, consider using [`layout-bottom`](../guide/extending-default-theme#layout-slots) slot instead.
:::
Note that footer will not be displayed when the [SideBar](./default-theme-sidebar) is visible.
## Frontmatter Config
This can be disabled per-page using the `footer` option on frontmatter:
```yaml
---
footer: false
---
```

@ -0,0 +1,195 @@
# Home Page
VitePress default theme provides a homepage layout, which you can also see used on [the homepage of this site](../). You may use it on any of your pages by specifying `layout: home` in the [frontmatter](./frontmatter-config).
```yaml
---
layout: home
---
```
However, this option alone wouldn't do much. You can add several different pre templated "sections" to the homepage by setting additional other options such as `hero` and `features`.
## Hero Section
The Hero section comes at the top of the homepage. Here's how you can configure the Hero section.
```yaml
---
layout: home
hero:
name: VitePress
text: Vite & Vue powered static site generator.
tagline: Lorem ipsum...
image:
src: /logo.png
alt: VitePress
actions:
- theme: brand
text: Get Started
link: /guide/what-is-vitepress
- theme: alt
text: View on GitHub
link: https://github.com/vuejs/vitepress
---
```
```ts
interface Hero {
// The string shown top of `text`. Comes with brand color
// and expected to be short, such as product name.
name?: string
// The main text for the hero section. This will be defined
// as `h1` tag.
text: string
// Tagline displayed below `text`.
tagline?: string
// The image is displayed next to the text and tagline area.
image?: ThemeableImage
// Action buttons to display in home hero section.
actions?: HeroAction[]
}
type ThemeableImage =
| string
| { src: string; alt?: string }
| { light: string; dark: string; alt?: string }
interface HeroAction {
// Color theme of the button. Defaults to `brand`.
theme?: 'brand' | 'alt'
// Label of the button.
text: string
// Destination link of the button.
link: string
// Link target attribute.
target?: string
// Link rel attribute.
rel?: string
}
```
### Customizing the name color
VitePress uses the brand color (`--vp-c-brand-1`) for the `name`. However, you may customize this color by overriding `--vp-home-hero-name-color` variable.
```css
:root {
--vp-home-hero-name-color: blue;
}
```
Also you may customize it further by combining `--vp-home-hero-name-background` to give the `name` gradient color.
```css
:root {
--vp-home-hero-name-color: transparent;
--vp-home-hero-name-background: -webkit-linear-gradient(120deg, #bd34fe, #41d1ff);
}
```
## Features Section
In Features section, you can list any number of features you would like to show right after the Hero section. To configure it, pass `features` option to the frontmatter.
You can provide an icon for each feature, which can be an emoji or any type of image. When the configured icon is an image (svg, png, jpeg...), you must provide the icon with the proper width and height; you can also provide the description, its intrinsic size as well as its variants for dark and light theme when required.
```yaml
---
layout: home
features:
- icon: 🛠️
title: Simple and minimal, always
details: Lorem ipsum...
- icon:
src: /cool-feature-icon.svg
title: Another cool feature
details: Lorem ipsum...
- icon:
dark: /dark-feature-icon.svg
light: /light-feature-icon.svg
title: Another cool feature
details: Lorem ipsum...
---
```
```ts
interface Feature {
// Show icon on each feature box.
icon?: FeatureIcon
// Title of the feature.
title: string
// Details of the feature.
details: string
// Link when clicked on feature component. The link can
// be both internal or external.
//
// e.g. `guide/reference/default-theme-home-page` or `https://example.com`
link?: string
// Link text to be shown inside feature component. Best
// used with `link` option.
//
// e.g. `Learn more`, `Visit page`, etc.
linkText?: string
// Link rel attribute for the `link` option.
//
// e.g. `external`
rel?: string
// Link target attribute for the `link` option.
target?: string
}
type FeatureIcon =
| string
| { src: string; alt?: string; width?: string; height: string }
| {
light: string
dark: string
alt?: string
width?: string
height: string
}
```
## Markdown Content
You can add additional content to your site's homepage just by adding Markdown below the `---` frontmatter divider.
````md
---
layout: home
hero:
name: VitePress
text: Vite & Vue powered static site generator.
---
## Getting Started
You can get started using VitePress right away using `npx`!
```sh
npm init
npx vitepress init
```
````
::: info
VitePress didn't always auto-style the extra content of the `layout: home` page. To revert to older behavior, you can add `markdownStyles: false` to the frontmatter.
:::

@ -0,0 +1,46 @@
# Last Updated
The update time of the last content will be displayed in the lower right corner of the page. To enable it, add `lastUpdated` options to your config.
::: info
VitePress displays the "last updated" time using the timestamp of the most recent Git commit for each file. To enable this, the Markdown file must be committed to Git.
Internally, VitePress runs `git log -1 --pretty="%ai"` on each file to retrieve its timestamp. If all pages show the same update time, it's likely due to shallow cloning (common in CI environments), which limits Git history.
To fix this in **GitHub Actions**, use the following in your workflow:
```yaml{4}
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0
```
Other CI/CD platforms have similar settings.
If such options aren't available, you can prepend the `docs:build` command in your `package.json` with a manual fetch:
```json
"docs:build": "git fetch --unshallow && vitepress build docs"
```
:::
## Site-Level Config
```js
export default {
lastUpdated: true
}
```
## Frontmatter Config
This can be disabled per-page using the `lastUpdated` option on frontmatter:
```yaml
---
lastUpdated: false
---
```
Also refer [Default Theme: Last Updated](./default-theme-config#lastupdated) for more details. Any truthy value at theme-level will also enable the feature unless explicitly disabled at site or page level.

@ -0,0 +1,62 @@
# Layout
You may choose the page layout by setting `layout` option to the page [frontmatter](./frontmatter-config). There are 3 layout options, `doc`, `page`, and `home`. If nothing is specified, then the page is treated as `doc` page.
```yaml
---
layout: doc
---
```
## Doc Layout
Option `doc` is the default layout and it styles the whole Markdown content into "documentation" look. It works by wrapping whole content within `vp-doc` css class, and applying styles to elements underneath it.
Almost all generic elements such as `p`, or `h2` get special styling. Therefore, keep in mind that if you add any custom HTML inside a Markdown content, those will get affected by those styles as well.
It also provides documentation specific features listed below. These features are only enabled in this layout.
- Edit Link
- Prev Next Link
- Outline
- [Carbon Ads](./default-theme-carbon-ads)
## Page Layout
Option `page` is treated as "blank page". The Markdown will still be parsed, and all of the [Markdown Extensions](../guide/markdown) work as same as `doc` layout, but it wouldn't get any default stylings.
The page layout will let you style everything by you without VitePress theme affecting the markup. This is useful when you want to create your own custom page.
Note that even in this layout, sidebar will still show up if the page has a matching sidebar config.
## Home Layout
Option `home` will generate templated "Homepage". In this layout, you can set extra options such as `hero` and `features` to customize the content further. Please visit [Default Theme: Home Page](./default-theme-home-page) for more details.
## No Layout
If you don't want any layout, you can pass `layout: false` through frontmatter. This option is helpful if you want a fully-customizable landing page (without any sidebar, navbar, or footer by default).
## Custom Layout
You can also use a custom layout:
```md
---
layout: foo
---
```
This will look for a component named `foo` registered in context. For example, you can register your component globally in `.vitepress/theme/index.ts`:
```ts
import DefaultTheme from 'vitepress/theme'
import Foo from './Foo.vue'
export default {
extends: DefaultTheme,
enhanceApp({ app }) {
app.component('foo', Foo)
}
}
```

@ -0,0 +1,216 @@
# Nav
The Nav is the navigation bar displayed on top of the page. It contains the site title, global menu links, etc.
## Site Title and Logo
By default, nav shows the title of the site referencing [`config.title`](./site-config#title) value. If you would like to change what's displayed on nav, you may define custom text in `themeConfig.siteTitle` option.
```js
export default {
themeConfig: {
siteTitle: 'My Custom Title'
}
}
```
If you have a logo for your site, you can display it by passing in the path to the image. You should place the logo within `public` directly, and define the absolute path to it.
```js
export default {
themeConfig: {
logo: '/my-logo.svg'
}
}
```
When adding a logo, it gets displayed along with the site title. If your logo is all you need and if you would like to hide the site title text, set `false` to the `siteTitle` option.
```js
export default {
themeConfig: {
logo: '/my-logo.svg',
siteTitle: false
}
}
```
You can also pass an object as logo if you want to add `alt` attribute or customize it based on dark/light mode. Refer [`themeConfig.logo`](./default-theme-config#logo) for details.
## Navigation Links
You may define `themeConfig.nav` option to add links to your nav.
```js
export default {
themeConfig: {
nav: [
{ text: 'Guide', link: '/guide' },
{ text: 'Config', link: '/config' },
{ text: 'Changelog', link: 'https://github.com/...' }
]
}
}
```
The `text` is the actual text displayed in nav, and the `link` is the link that will be navigated to when the text is clicked. For the link, set path to the actual file without `.md` prefix, and always start with `/`.
The `link` can also be a function that accepts [`PageData`](./runtime-api#usedata) as the argument and returns the path.
Nav links can also be dropdown menus. To do this, set `items` key on link option.
```js
export default {
themeConfig: {
nav: [
{ text: 'Guide', link: '/guide' },
{
text: 'Dropdown Menu',
items: [
{ text: 'Item A', link: '/item-1' },
{ text: 'Item B', link: '/item-2' },
{ text: 'Item C', link: '/item-3' }
]
}
]
}
}
```
Note that dropdown menu title (`Dropdown Menu` in the above example) can not have `link` property since it becomes a button to open dropdown dialog.
You may further add "sections" to the dropdown menu items as well by passing in more nested items.
```js
export default {
themeConfig: {
nav: [
{ text: 'Guide', link: '/guide' },
{
text: 'Dropdown Menu',
items: [
{
// Title for the section.
text: 'Section A Title',
items: [
{ text: 'Section A Item A', link: '...' },
{ text: 'Section B Item B', link: '...' }
]
}
]
},
{
text: 'Dropdown Menu',
items: [
{
// You may also omit the title.
items: [
{ text: 'Section A Item A', link: '...' },
{ text: 'Section B Item B', link: '...' }
]
}
]
}
]
}
}
```
### Customize link's "active" state
Nav menu items will be highlighted when the current page is under the matching path. if you would like to customize the path to be matched, define `activeMatch` property and regex as a string value.
```js
export default {
themeConfig: {
nav: [
// This link gets active state when the user is
// on `/config/` path.
{
text: 'Guide',
link: '/guide',
activeMatch: '/config/'
}
]
}
}
```
::: warning
`activeMatch` is expected to be a regex string, but you must define it as a string. We can't use actual RegExp object here because it isn't serializable during the build time.
:::
### Customize link's "target" and "rel" attributes
By default, VitePress automatically determines `target` and `rel` attributes based on whether the link is an external link. But if you want, you can customize them too.
```js
export default {
themeConfig: {
nav: [
{
text: 'Merchandise',
link: 'https://www.thegithubshop.com/',
target: '_self',
rel: 'sponsored'
}
]
}
}
```
## Social Links
Refer [`socialLinks`](./default-theme-config#sociallinks).
## Custom Components
You can include custom components in the navigation bar by using the `component` option. The `component` key should be the Vue component name, and must be registered globally using [Theme.enhanceApp](../guide/custom-theme#theme-interface).
```js [.vitepress/config.js]
export default {
themeConfig: {
nav: [
{
text: 'My Menu',
items: [
{
component: 'MyCustomComponent',
// Optional props to pass to the component
props: {
title: 'My Custom Component'
}
}
]
},
{
component: 'AnotherCustomComponent'
}
]
}
}
```
Then, you need to register the component globally:
```js [.vitepress/theme/index.js]
import DefaultTheme from 'vitepress/theme'
import MyCustomComponent from './components/MyCustomComponent.vue'
import AnotherCustomComponent from './components/AnotherCustomComponent.vue'
/** @type {import('vitepress').Theme} */
export default {
extends: DefaultTheme,
enhanceApp({ app }) {
app.component('MyCustomComponent', MyCustomComponent)
app.component('AnotherCustomComponent', AnotherCustomComponent)
}
}
```
Your component will be rendered in the navigation bar. VitePress will provide the following additional props to the component:
- `screenMenu`: an optional boolean indicating whether the component is inside mobile navigation menu
You can check an example in the e2e tests [here](https://github.com/vuejs/vitepress/tree/main/__tests__/e2e/.vitepress).

@ -0,0 +1,43 @@
# Prev Next Links
You can customize the text and link for the previous and next pages (shown at doc footer). This is helpful if you want a different text there than what you have on your sidebar. Additionally, you may find it useful to disable the footer or link to a page that is not included in your sidebar.
## prev
- Type: `string | false | { text?: string; link?: string }`
- Details:
Specifies the text/link to show on the link to the previous page. If you don't set this in frontmatter, the text/link will be inferred from the sidebar config.
- Examples:
- To customize only the text:
```yaml
---
prev: 'Get Started | Markdown'
---
```
- To customize both text and link:
```yaml
---
prev:
text: 'Markdown'
link: '/guide/markdown'
---
```
- To hide previous page:
```yaml
---
prev: false
---
```
## next
Same as `prev` but for the next page.

@ -0,0 +1,451 @@
---
outline: deep
---
# Search
## Local Search
VitePress supports fuzzy full-text search using an in-browser index thanks to [minisearch](https://github.com/lucaong/minisearch/). To enable this feature, simply set the `themeConfig.search.provider` option to `'local'` in your `.vitepress/config.ts` file:
```ts
import { defineConfig } from 'vitepress'
export default defineConfig({
themeConfig: {
search: {
provider: 'local'
}
}
})
```
Example result:
![screenshot of the search modal](/search.png)
Alternatively, you can use [Algolia DocSearch](#algolia-search) or some community plugins like:
- <https://www.npmjs.com/package/vitepress-plugin-search>
- <https://www.npmjs.com/package/vitepress-plugin-pagefind>
- <https://www.npmjs.com/package/@orama/plugin-vitepress>
### i18n {#local-search-i18n}
You can use a config like this to use multilingual search:
```ts
import { defineConfig } from 'vitepress'
export default defineConfig({
themeConfig: {
search: {
provider: 'local',
options: {
locales: {
zh: { // make this `root` if you want to translate the default locale
translations: {
button: {
buttonText: '搜索',
buttonAriaLabel: '搜索'
},
modal: {
displayDetails: '显示详细列表',
resetButtonTitle: '重置搜索',
backButtonTitle: '关闭搜索',
noResultsText: '没有结果',
footer: {
selectText: '选择',
selectKeyAriaLabel: '输入',
navigateText: '导航',
navigateUpKeyAriaLabel: '上箭头',
navigateDownKeyAriaLabel: '下箭头',
closeText: '关闭',
closeKeyAriaLabel: 'esc'
}
}
}
}
}
}
}
}
})
```
### miniSearch options
You can configure MiniSearch like this:
```ts
import { defineConfig } from 'vitepress'
export default defineConfig({
themeConfig: {
search: {
provider: 'local',
options: {
miniSearch: {
/**
* @type {Pick<import('minisearch').Options, 'extractField' | 'tokenize' | 'processTerm'>}
*/
options: {
/* ... */
},
/**
* @type {import('minisearch').SearchOptions}
* @default
* { fuzzy: 0.2, prefix: true, boost: { title: 4, text: 2, titles: 1 } }
*/
searchOptions: {
/* ... */
}
}
}
}
}
})
```
Learn more in [MiniSearch docs](https://lucaong.github.io/minisearch/classes/MiniSearch.MiniSearch.html).
### Custom content renderer
You can customize the function used to render the markdown content before indexing it:
```ts
import { defineConfig } from 'vitepress'
export default defineConfig({
themeConfig: {
search: {
provider: 'local',
options: {
/**
* @param {string} src
* @param {import('vitepress').MarkdownEnv} env
* @param {import('markdown-it-async')} md
*/
async _render(src, env, md) {
// return html string
}
}
}
}
})
```
This function will be stripped from client-side site data, so you can use Node.js APIs in it.
#### Example: Excluding pages from search
You can exclude pages from search by adding `search: false` to the frontmatter of the page. Alternatively:
```ts
import { defineConfig } from 'vitepress'
export default defineConfig({
themeConfig: {
search: {
provider: 'local',
options: {
async _render(src, env, md) {
const html = await md.renderAsync(src, env)
if (env.frontmatter?.search === false) return ''
if (env.relativePath.startsWith('some/path')) return ''
return html
}
}
}
}
})
```
::: warning Note
In case a custom `_render` function is provided, you need to handle the `search: false` frontmatter yourself. Also, the `env` object won't be completely populated before `md.renderAsync` is called, so any checks on optional `env` properties like `frontmatter` should be done after that.
:::
#### Example: Transforming content - adding anchors
```ts
import { defineConfig } from 'vitepress'
export default defineConfig({
themeConfig: {
search: {
provider: 'local',
options: {
async _render(src, env, md) {
const html = await md.renderAsync(src, env)
if (env.frontmatter?.title)
return await md.renderAsync(`# ${env.frontmatter.title}`) + html
return html
}
}
}
}
})
```
## Algolia Search
VitePress supports searching your docs site using [Algolia DocSearch](https://docsearch.algolia.com/docs/what-is-docsearch). Refer their getting started guide. In your `.vitepress/config.ts` you'll need to provide at least the following to make it work:
```ts
import { defineConfig } from 'vitepress'
export default defineConfig({
themeConfig: {
search: {
provider: 'algolia',
options: {
appId: '...',
apiKey: '...',
indexName: '...'
}
}
}
})
```
### i18n {#algolia-search-i18n}
You can use a config like this to use multilingual search:
```ts
import { defineConfig } from 'vitepress'
export default defineConfig({
themeConfig: {
search: {
provider: 'algolia',
options: {
appId: '...',
apiKey: '...',
indexName: '...',
locales: {
zh: {
placeholder: '搜索文档',
translations: {
button: {
buttonText: '搜索文档',
buttonAriaLabel: '搜索文档'
},
modal: {
searchBox: {
clearButtonTitle: '清除查询条件',
clearButtonAriaLabel: '清除查询条件',
closeButtonText: '关闭',
closeButtonAriaLabel: '关闭',
placeholderText: '搜索文档',
placeholderTextAskAi: '向 AI 提问:',
placeholderTextAskAiStreaming: '回答中...',
searchInputLabel: '搜索',
backToKeywordSearchButtonText: '返回关键字搜索',
backToKeywordSearchButtonAriaLabel: '返回关键字搜索'
},
startScreen: {
recentSearchesTitle: '搜索历史',
noRecentSearchesText: '没有搜索历史',
saveRecentSearchButtonTitle: '保存至搜索历史',
removeRecentSearchButtonTitle: '从搜索历史中移除',
favoriteSearchesTitle: '收藏',
removeFavoriteSearchButtonTitle: '从收藏中移除',
recentConversationsTitle: '最近的对话',
removeRecentConversationButtonTitle: '从历史记录中删除对话'
},
errorScreen: {
titleText: '无法获取结果',
helpText: '你可能需要检查你的网络连接'
},
noResultsScreen: {
noResultsText: '无法找到相关结果',
suggestedQueryText: '你可以尝试查询',
reportMissingResultsText: '你认为该查询应该有结果?',
reportMissingResultsLinkText: '点击反馈'
},
resultsScreen: {
askAiPlaceholder: '向 AI 提问: '
},
askAiScreen: {
disclaimerText: '答案由 AI 生成,可能不准确,请自行验证。',
relatedSourcesText: '相关来源',
thinkingText: '思考中...',
copyButtonText: '复制',
copyButtonCopiedText: '已复制!',
copyButtonTitle: '复制',
likeButtonTitle: '赞',
dislikeButtonTitle: '踩',
thanksForFeedbackText: '感谢你的反馈!',
preToolCallText: '搜索中...',
duringToolCallText: '搜索 ',
afterToolCallText: '已搜索'
},
footer: {
selectText: '选择',
submitQuestionText: '提交问题',
selectKeyAriaLabel: 'Enter 键',
navigateText: '切换',
navigateUpKeyAriaLabel: '向上箭头',
navigateDownKeyAriaLabel: '向下箭头',
closeText: '关闭',
backToSearchText: '返回搜索',
closeKeyAriaLabel: 'Esc 键',
poweredByText: '搜索提供者'
}
}
}
}
}
}
}
}
})
```
[These options](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts) can be overridden. Refer official Algolia docs to learn more about them.
### Algolia Ask AI Support {#ask-ai}
If you would like to include **Ask AI**, pass the `askAi` option (or any of the partial fields) inside `options`:
```ts
import { defineConfig } from 'vitepress'
export default defineConfig({
themeConfig: {
search: {
provider: 'algolia',
options: {
appId: '...',
apiKey: '...',
indexName: '...',
// askAi: "YOUR-ASSISTANT-ID"
// OR
askAi: {
// at minimum you must provide the assistantId you received from Algolia
assistantId: 'XXXYYY',
// optional overrides if omitted, the top-level appId/apiKey/indexName values are reused
// apiKey: '...',
// appId: '...',
// indexName: '...'
}
}
}
}
})
```
::: warning Note
If want to default to keyword search and do not want to use Ask AI, just omit the `askAi` property
:::
The translations for the Ask AI UI live under `options.translations.modal.askAiScreen` and `options.translations.resultsScreen` — see the [type definitions](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts) for all keys.
### Crawler Config
Here is an example config based on what this site uses:
```ts
new Crawler({
appId: '...',
apiKey: '...',
rateLimit: 8,
startUrls: ['https://vitepress.dev/'],
renderJavaScript: false,
sitemaps: [],
exclusionPatterns: [],
ignoreCanonicalTo: false,
discoveryPatterns: ['https://vitepress.dev/**'],
schedule: 'at 05:10 on Saturday',
actions: [
{
indexName: 'vitepress',
pathsToMatch: ['https://vitepress.dev/**'],
recordExtractor: ({ $, helpers }) => {
return helpers.docsearch({
recordProps: {
lvl1: '.content h1',
content: '.content p, .content li',
lvl0: {
selectors: 'section.has-active div h2',
defaultValue: 'Documentation'
},
lvl2: '.content h2',
lvl3: '.content h3',
lvl4: '.content h4',
lvl5: '.content h5'
},
indexHeadings: true
})
}
}
],
initialIndexSettings: {
vitepress: {
attributesForFaceting: ['type', 'lang'],
attributesToRetrieve: ['hierarchy', 'content', 'anchor', 'url'],
attributesToHighlight: ['hierarchy', 'hierarchy_camel', 'content'],
attributesToSnippet: ['content:10'],
camelCaseAttributes: ['hierarchy', 'hierarchy_radio', 'content'],
searchableAttributes: [
'unordered(hierarchy_radio_camel.lvl0)',
'unordered(hierarchy_radio.lvl0)',
'unordered(hierarchy_radio_camel.lvl1)',
'unordered(hierarchy_radio.lvl1)',
'unordered(hierarchy_radio_camel.lvl2)',
'unordered(hierarchy_radio.lvl2)',
'unordered(hierarchy_radio_camel.lvl3)',
'unordered(hierarchy_radio.lvl3)',
'unordered(hierarchy_radio_camel.lvl4)',
'unordered(hierarchy_radio.lvl4)',
'unordered(hierarchy_radio_camel.lvl5)',
'unordered(hierarchy_radio.lvl5)',
'unordered(hierarchy_radio_camel.lvl6)',
'unordered(hierarchy_radio.lvl6)',
'unordered(hierarchy_camel.lvl0)',
'unordered(hierarchy.lvl0)',
'unordered(hierarchy_camel.lvl1)',
'unordered(hierarchy.lvl1)',
'unordered(hierarchy_camel.lvl2)',
'unordered(hierarchy.lvl2)',
'unordered(hierarchy_camel.lvl3)',
'unordered(hierarchy.lvl3)',
'unordered(hierarchy_camel.lvl4)',
'unordered(hierarchy.lvl4)',
'unordered(hierarchy_camel.lvl5)',
'unordered(hierarchy.lvl5)',
'unordered(hierarchy_camel.lvl6)',
'unordered(hierarchy.lvl6)',
'content'
],
distinct: true,
attributeForDistinct: 'url',
customRanking: [
'desc(weight.pageRank)',
'desc(weight.level)',
'asc(weight.position)'
],
ranking: [
'words',
'filters',
'typo',
'attribute',
'proximity',
'exact',
'custom'
],
highlightPreTag: '<span class="algolia-docsearch-suggestion--highlight">',
highlightPostTag: '</span>',
minWordSizefor1Typo: 3,
minWordSizefor2Typos: 7,
allowTyposOnNumericTokens: false,
minProximity: 1,
ignorePlurals: true,
advancedSyntax: true,
attributeCriteriaComputedByMinProximity: true,
removeWordsIfNoResults: 'allOptional'
}
}
})
```

@ -0,0 +1,182 @@
# Sidebar
The sidebar is the main navigation block for your documentation. You can configure the sidebar menu in [`themeConfig.sidebar`](./default-theme-config#sidebar).
```js
export default {
themeConfig: {
sidebar: [
{
text: 'Guide',
items: [
{ text: 'Introduction', link: '/introduction' },
{ text: 'Getting Started', link: '/getting-started' },
...
]
}
]
}
}
```
## The Basics
The simplest form of the sidebar menu is passing in a single array of links. The first level item defines the "section" for the sidebar. It should contain `text`, which is the title of the section, and `items` which are the actual navigation links.
```js
export default {
themeConfig: {
sidebar: [
{
text: 'Section Title A',
items: [
{ text: 'Item A', link: '/item-a' },
{ text: 'Item B', link: '/item-b' },
...
]
},
{
text: 'Section Title B',
items: [
{ text: 'Item C', link: '/item-c' },
{ text: 'Item D', link: '/item-d' },
...
]
}
]
}
}
```
Each `link` should specify the path to the actual file starting with `/`. If you add trailing slash to the end of link, it will show `index.md` of the corresponding directory.
```js
export default {
themeConfig: {
sidebar: [
{
text: 'Guide',
items: [
// This shows `/guide/index.md` page.
{ text: 'Introduction', link: '/guide/' }
]
}
]
}
}
```
You may further nest the sidebar items up to 6 level deep counting up from the root level. Note that deeper than 6 level of nested items gets ignored and will not be displayed on the sidebar.
```js
export default {
themeConfig: {
sidebar: [
{
text: 'Level 1',
items: [
{
text: 'Level 2',
items: [
{
text: 'Level 3',
items: [
...
]
}
]
}
]
}
]
}
}
```
## Multiple Sidebars
You may show different sidebar depending on the page path. For example, as shown on this site, you might want to create a separate sections of content in your documentation like "Guide" page and "Config" page.
To do so, first organize your pages into directories for each desired section:
```
.
├─ guide/
│ ├─ index.md
│ ├─ one.md
│ └─ two.md
└─ config/
├─ index.md
├─ three.md
└─ four.md
```
Then, update your configuration to define your sidebar for each section. This time, you should pass an object instead of an array.
```js
export default {
themeConfig: {
sidebar: {
// This sidebar gets displayed when a user
// is on `guide` directory.
'/guide/': [
{
text: 'Guide',
items: [
{ text: 'Index', link: '/guide/' },
{ text: 'One', link: '/guide/one' },
{ text: 'Two', link: '/guide/two' }
]
}
],
// This sidebar gets displayed when a user
// is on `config` directory.
'/config/': [
{
text: 'Config',
items: [
{ text: 'Index', link: '/config/' },
{ text: 'Three', link: '/config/three' },
{ text: 'Four', link: '/config/four' }
]
}
]
}
}
}
```
## Collapsible Sidebar Groups
By adding `collapsed` option to the sidebar group, it shows a toggle button to hide/show each section.
```js
export default {
themeConfig: {
sidebar: [
{
text: 'Section Title A',
collapsed: false,
items: [...]
}
]
}
}
```
All sections are "open" by default. If you would like them to be "closed" on initial page load, set `collapsed` option to `true`.
```js
export default {
themeConfig: {
sidebar: [
{
text: 'Section Title A',
collapsed: true,
items: [...]
}
]
}
}
```

@ -0,0 +1,256 @@
<script setup>
import { VPTeamMembers } from 'vitepress/theme'
const members = [
{
avatar: 'https://github.com/yyx990803.png',
name: 'Evan You',
title: 'Creator',
links: [
{ icon: 'github', link: 'https://github.com/yyx990803' },
{ icon: 'twitter', link: 'https://twitter.com/youyuxi' }
]
},
{
avatar: 'https://github.com/kiaking.png',
name: 'Kia King Ishii',
title: 'Developer',
links: [
{ icon: 'github', link: 'https://github.com/kiaking' },
{ icon: 'twitter', link: 'https://twitter.com/KiaKing85' }
]
}
]
</script>
# Team Page
If you would like to introduce your team, you may use Team components to construct the Team Page. There are two ways of using these components. One is to embed it in doc page, and another is to create a full Team Page.
## Show team members in a page
You may use `<VPTeamMembers>` component exposed from `vitepress/theme` to display a list of team members on any page.
```html
<script setup>
import { VPTeamMembers } from 'vitepress/theme'
const members = [
{
avatar: 'https://www.github.com/yyx990803.png',
name: 'Evan You',
title: 'Creator',
links: [
{ icon: 'github', link: 'https://github.com/yyx990803' },
{ icon: 'twitter', link: 'https://twitter.com/youyuxi' }
]
},
...
]
</script>
# Our Team
Say hello to our awesome team.
<VPTeamMembers size="small" :members />
```
The above will display a team member in card looking element. It should display something similar to below.
<VPTeamMembers size="small" :members />
`<VPTeamMembers>` component comes in 2 different sizes, `small` and `medium`. While it boils down to your preference, usually `small` size should fit better when used in doc page. Also, you may add more properties to each member such as adding "description" or "sponsor" button. Learn more about it in [`<VPTeamMembers>`](#vpteammembers).
Embedding team members in doc page is good for small size team where having dedicated full team page might be too much, or introducing partial members as a reference to documentation context.
If you have large number of members, or simply would like to have more space to show team members, consider [creating a full team page](#create-a-full-team-page).
## Create a full Team Page
Instead of adding team members to doc page, you may also create a full Team Page, similar to how you can create a custom [Home Page](./default-theme-home-page).
To create a team page, first, create a new md file. The file name doesn't matter, but here lets call it `team.md`. In this file, set frontmatter option `layout: page`, and then you may compose your page structure using `TeamPage` components.
```html
---
layout: page
---
<script setup>
import {
VPTeamPage,
VPTeamPageTitle,
VPTeamMembers
} from 'vitepress/theme'
const members = [
{
avatar: 'https://www.github.com/yyx990803.png',
name: 'Evan You',
title: 'Creator',
links: [
{ icon: 'github', link: 'https://github.com/yyx990803' },
{ icon: 'twitter', link: 'https://twitter.com/youyuxi' }
]
},
...
]
</script>
<VPTeamPage>
<VPTeamPageTitle>
<template #title>
Our Team
</template>
<template #lead>
The development of VitePress is guided by an international
team, some of whom have chosen to be featured below.
</template>
</VPTeamPageTitle>
<VPTeamMembers :members />
</VPTeamPage>
```
When creating a full team page, remember to wrap all components with `<VPTeamPage>` component. This component will ensure all nested team related components get the proper layout structure like spacings.
`<VPPageTitle>` component adds the page title section. The title being `<h1>` heading. Use `#title` and `#lead` slot to document about your team.
`<VPMembers>` works as same as when used in a doc page. It will display list of members.
### Add sections to divide team members
You may add "sections" to the team page. For example, you may have different types of team members such as Core Team Members and Community Partners. You can divide these members into sections to better explain the roles of each group.
To do so, add `<VPTeamPageSection>` component to the `team.md` file we created previously.
```html
---
layout: page
---
<script setup>
import {
VPTeamPage,
VPTeamPageTitle,
VPTeamMembers,
VPTeamPageSection
} from 'vitepress/theme'
const coreMembers = [...]
const partners = [...]
</script>
<VPTeamPage>
<VPTeamPageTitle>
<template #title>Our Team</template>
<template #lead>...</template>
</VPTeamPageTitle>
<VPTeamMembers size="medium" :members="coreMembers" />
<VPTeamPageSection>
<template #title>Partners</template>
<template #lead>...</template>
<template #members>
<VPTeamMembers size="small" :members="partners" />
</template>
</VPTeamPageSection>
</VPTeamPage>
```
The `<VPTeamPageSection>` component can have `#title` and `#lead` slot similar to `VPTeamPageTitle` component, and also `#members` slot for displaying team members.
Remember to put in `<VPTeamMembers>` component within `#members` slot.
## `<VPTeamMembers>`
The `<VPTeamMembers>` component displays a given list of members.
```html
<VPTeamMembers
size="medium"
:members="[
{ avatar: '...', name: '...' },
{ avatar: '...', name: '...' },
...
]"
/>
```
```ts
interface Props {
// Size of each members. Defaults to `medium`.
size?: 'small' | 'medium'
// List of members to display.
members: TeamMember[]
}
interface TeamMember {
// Avatar image for the member.
avatar: string
// Name of the member.
name: string
// Title to be shown below member's name.
// e.g. Developer, Software Engineer, etc.
title?: string
// Organization that the member belongs.
org?: string
// URL for the organization.
orgLink?: string
// Description for the member.
desc?: string
// Social links. e.g. GitHub, Twitter, etc. You may pass in
// the Social Links object here.
// See: https://vitepress.dev/reference/default-theme-config.html#sociallinks
links?: SocialLink[]
// URL for the sponsor page for the member.
sponsor?: string
// Text for the sponsor link. Defaults to 'Sponsor'.
actionText?: string
}
```
## `<VPTeamPage>`
The root component when creating a full team page. It only accepts a single slot. It will style all passed in team related components.
## `<VPTeamPageTitle>`
Adds "title" section of the page. Best use at the very beginning under `<VPTeamPage>`. It accepts `#title` and `#lead` slot.
```html
<VPTeamPage>
<VPTeamPageTitle>
<template #title>
Our Team
</template>
<template #lead>
The development of VitePress is guided by an international
team, some of whom have chosen to be featured below.
</template>
</VPTeamPageTitle>
</VPTeamPage>
```
## `<VPTeamPageSection>`
Creates a "section" with in team page. It accepts `#title`, `#lead`, and `#members` slot. You may add as many sections as you like inside `<VPTeamPage>`.
```html
<VPTeamPage>
...
<VPTeamPageSection>
<template #title>Partners</template>
<template #lead>Lorem ipsum...</template>
<template #members>
<VPTeamMembers :members="data" />
</template>
</VPTeamPageSection>
</VPTeamPage>
```

@ -0,0 +1,240 @@
---
outline: deep
---
# Frontmatter Config
Frontmatter enables page based configuration. In every markdown file, you can use frontmatter config to override site-level or theme-level config options. Also, there are config options which you can only define in frontmatter.
Example usage:
```md
---
title: Docs with VitePress
editLink: true
---
```
You can access frontmatter data via the `$frontmatter` global in Vue expressions:
```md
{{ $frontmatter.title }}
```
## title
- Type: `string`
Title for the page. It's same as [config.title](./site-config#title), and it overrides the site-level config.
```yaml
---
title: VitePress
---
```
## titleTemplate
- Type: `string | boolean`
The suffix for the title. It's same as [config.titleTemplate](./site-config#titletemplate), and it overrides the site-level config.
```yaml
---
title: VitePress
titleTemplate: Vite & Vue powered static site generator
---
```
## description
- Type: `string`
Description for the page. It's same as [config.description](./site-config#description), and it overrides the site-level config.
```yaml
---
description: VitePress
---
```
## head
- Type: `HeadConfig[]`
Specify extra head tags to be injected for the current page. Will be appended after head tags injected by site-level config.
```yaml
---
head:
- - meta
- name: description
content: hello
- - meta
- name: keywords
content: super duper SEO
---
```
```ts
type HeadConfig =
| [string, Record<string, string>]
| [string, Record<string, string>, string]
```
## Default Theme Only
The following frontmatter options are only applicable when using the default theme.
### layout
- Type: `doc | home | page`
- Default: `doc`
Determines the layout of the page.
- `doc` - It applies default documentation styles to the markdown content.
- `home` - Special layout for "Home Page". You may add extra options such as `hero` and `features` to rapidly create beautiful landing page.
- `page` - Behave similar to `doc` but it applies no styles to the content. Useful when you want to create a fully custom page.
```yaml
---
layout: doc
---
```
### hero <Badge type="info" text="home page only" />
Defines contents of home hero section when `layout` is set to `home`. More details in [Default Theme: Home Page](./default-theme-home-page).
### features <Badge type="info" text="home page only" />
Defines items to display in features section when `layout` is set to `home`. More details in [Default Theme: Home Page](./default-theme-home-page).
### navbar
- Type: `boolean`
- Default: `true`
Whether to display [navbar](./default-theme-nav).
```yaml
---
navbar: false
---
```
### sidebar
- Type: `boolean`
- Default: `true`
Whether to display [sidebar](./default-theme-sidebar).
```yaml
---
sidebar: false
---
```
### aside
- Type: `boolean | 'left'`
- Default: `true`
Defines the location of the aside component in the `doc` layout.
Setting this value to `false` prevents rendering of aside container.\
Setting this value to `true` renders the aside to the right.\
Setting this value to `'left'` renders the aside to the left.
```yaml
---
aside: false
---
```
### outline
- Type: `number | [number, number] | 'deep' | false`
- Default: `2`
The levels of header in the outline to display for the page. It's same as [config.themeConfig.outline.level](./default-theme-config#outline), and it overrides the value set in site-level config.
```yaml
---
outline: [2, 4]
---
```
### lastUpdated
- Type: `boolean | Date`
- Default: `true`
Whether to display [last updated](./default-theme-last-updated) text in the footer of the current page. If a datetime is specified, it will be displayed instead of the last git modified timestamp.
```yaml
---
lastUpdated: false
---
```
### editLink
- Type: `boolean`
- Default: `true`
Whether to display [edit link](./default-theme-edit-link) in the footer of the current page.
```yaml
---
editLink: false
---
```
### footer
- Type: `boolean`
- Default: `true`
Whether to display [footer](./default-theme-footer).
```yaml
---
footer: false
---
```
### pageClass
- Type: `string`
Add extra class name to a specific page.
```yaml
---
pageClass: custom-page-class
---
```
Then you can customize styles of this specific page in `.vitepress/theme/custom.css` file:
```css
.custom-page-class {
/* page-specific styles */
}
```
### isHome
- Type: `boolean`
The default theme relies on checks like `frontmatter.layout === 'home'` to determine if the current page is the home page.\
This is useful when you want to force show the home page elements in a custom layout.
```yaml
---
isHome: true
---
```

@ -0,0 +1,173 @@
# Runtime API
VitePress offers several built-in APIs to let you access app data. VitePress also comes with a few built-in components that can be used globally.
The helper methods are globally importable from `vitepress` and are typically used in custom theme Vue components. However, they are also usable inside `.md` pages because markdown files are compiled into Vue [Single-File Components](https://vuejs.org/guide/scaling-up/sfc.html).
Methods that start with `use*` indicates that it is a [Vue 3 Composition API](https://vuejs.org/guide/introduction.html#composition-api) function ("Composable") that can only be used inside `setup()` or `<script setup>`.
## `useData` <Badge type="info" text="composable" />
Returns page-specific data. The returned object has the following type:
```ts
interface VitePressData<T = any> {
/**
* Site-level metadata
*/
site: Ref<SiteData<T>>
/**
* themeConfig from .vitepress/config.js
*/
theme: Ref<T>
/**
* Page-level metadata
*/
page: Ref<PageData>
/**
* Page frontmatter
*/
frontmatter: Ref<PageData['frontmatter']>
/**
* Dynamic route params
*/
params: Ref<PageData['params']>
title: Ref<string>
description: Ref<string>
lang: Ref<string>
isDark: Ref<boolean>
dir: Ref<string>
localeIndex: Ref<string>
/**
* Current location hash
*/
hash: Ref<string>
}
interface PageData {
title: string
titleTemplate?: string | boolean
description: string
relativePath: string
filePath: string,
headers: Header[]
frontmatter: Record<string, any>
params?: Record<string, any>
isNotFound?: boolean
lastUpdated?: number
}
```
**Example:**
```vue
<script setup>
import { useData } from 'vitepress'
const { theme } = useData()
</script>
<template>
<h1>{{ theme.footer.copyright }}</h1>
</template>
```
## `useRoute` <Badge type="info" text="composable" />
Returns the current route object with the following type:
```ts
interface Route {
path: string
data: PageData
component: Component | null
}
```
## `useRouter` <Badge type="info" text="composable" />
Returns the VitePress router instance so you can programmatically navigate to another page.
```ts
interface Router {
/**
* Current route.
*/
route: Route
/**
* Navigate to a new URL.
*/
go: (to?: string) => Promise<void>
/**
* Called before the route changes. Return `false` to cancel the navigation.
*/
onBeforeRouteChange?: (to: string) => Awaitable<void | boolean>
/**
* Called before the page component is loaded (after the history state is updated).
* Return `false` to cancel the navigation.
*/
onBeforePageLoad?: (to: string) => Awaitable<void | boolean>
/**
* Called after the page component is loaded (before the page component is updated).
*/
onAfterPageLoad?: (to: string) => Awaitable<void>
/**
* Called after the route changes.
*/
onAfterRouteChange?: (to: string) => Awaitable<void>
}
```
## `withBase` <Badge type="info" text="helper" />
- **Type**: `(path: string) => string`
Appends the configured [`base`](./site-config#base) to a given URL path. Also see [Base URL](../guide/asset-handling#base-url).
## `<Content />` <Badge type="info" text="component" />
The `<Content />` component displays the rendered markdown contents. Useful [when creating your own theme](../guide/custom-theme).
```vue
<template>
<h1>Custom Layout!</h1>
<Content />
</template>
```
## `<ClientOnly />` <Badge type="info" text="component" />
The `<ClientOnly />` component renders its slot only at client side.
Because VitePress applications are server-rendered in Node.js when generating static builds, any Vue usage must conform to the universal code requirements. In short, make sure to only access Browser / DOM APIs in beforeMount or mounted hooks.
If you are using or demoing components that are not SSR-friendly (for example, contain custom directives), you can wrap them inside the `ClientOnly` component.
```vue-html
<ClientOnly>
<NonSSRFriendlyComponent />
</ClientOnly>
```
- Related: [SSR Compatibility](../guide/ssr-compat)
## `$frontmatter` <Badge type="info" text="template global" />
Directly access current page's [frontmatter](../guide/frontmatter) data in Vue expressions.
```md
---
title: Hello
---
# {{ $frontmatter.title }}
```
## `$params` <Badge type="info" text="template global" />
Directly access current page's [dynamic route params](../guide/routing#dynamic-routes) in Vue expressions.
```md
- package name: {{ $params.pkg }}
- version: {{ $params.version }}
```

@ -0,0 +1,722 @@
---
outline: deep
---
# Site Config
Site config is where you can define the global settings of the site. App config options define settings that apply to every VitePress site, regardless of what theme it is using. For example, the base directory or the title of the site.
## Overview
### Config Resolution
The config file is always resolved from `<root>/.vitepress/config.[ext]`, where `<root>` is your VitePress [project root](../guide/routing#root-and-source-directory), and `[ext]` is one of the supported file extensions. TypeScript is supported out of the box. Supported extensions include `.js`, `.ts`, `.mjs`, and `.mts`.
It is recommended to use ES modules syntax in config files. The config file should default export an object:
```ts
export default {
// app level config options
lang: 'en-US',
title: 'VitePress',
description: 'Vite & Vue powered static site generator.',
...
}
```
::: details Dynamic (Async) Config
If you need to dynamically generate the config, you can also default export a function. For example:
```ts
import { defineConfig } from 'vitepress'
export default async () => {
const posts = await (await fetch('https://my-cms.com/blog-posts')).json()
return defineConfig({
// app level config options
lang: 'en-US',
title: 'VitePress',
description: 'Vite & Vue powered static site generator.',
// theme level config options
themeConfig: {
sidebar: [
...posts.map((post) => ({
text: post.name,
link: `/posts/${post.name}`
}))
]
}
})
}
```
You can also use top-level `await`. For example:
```ts
import { defineConfig } from 'vitepress'
const posts = await (await fetch('https://my-cms.com/blog-posts')).json()
export default defineConfig({
// app level config options
lang: 'en-US',
title: 'VitePress',
description: 'Vite & Vue powered static site generator.',
// theme level config options
themeConfig: {
sidebar: [
...posts.map((post) => ({
text: post.name,
link: `/posts/${post.name}`
}))
]
}
})
```
:::
### Config Intellisense
Using the `defineConfig` helper will provide TypeScript-powered intellisense for config options. Assuming your IDE supports it, this should work in both JavaScript and TypeScript.
```js
import { defineConfig } from 'vitepress'
export default defineConfig({
// ...
})
```
### Typed Theme Config
By default, `defineConfig` helper expects the theme config type from default theme:
```ts
import { defineConfig } from 'vitepress'
export default defineConfig({
themeConfig: {
// Type is `DefaultTheme.Config`
}
})
```
If you use a custom theme and want type checks for the theme config, you'll need to use `defineConfigWithTheme` instead, and pass the config type for your custom theme via a generic argument:
```ts
import { defineConfigWithTheme } from 'vitepress'
import type { ThemeConfig } from 'your-theme'
export default defineConfigWithTheme<ThemeConfig>({
themeConfig: {
// Type is `ThemeConfig`
}
})
```
### Vite, Vue & Markdown Config
- **Vite**
You can configure the underlying Vite instance using the [vite](#vite) option in your VitePress config. No need to create a separate Vite config file.
- **Vue**
VitePress already includes the official Vue plugin for Vite ([@vitejs/plugin-vue](https://github.com/vitejs/vite-plugin-vue)). You can configure its options using the [vue](#vue) option in your VitePress config.
- **Markdown**
You can configure the underlying [Markdown-It](https://github.com/markdown-it/markdown-it) instance using the [markdown](#markdown) option in your VitePress config.
## Site Metadata
### title
- Type: `string`
- Default: `VitePress`
- Can be overridden per page via [frontmatter](./frontmatter-config#title)
Title for the site. When using the default theme, this will be displayed in the nav bar.
It will also be used as the default suffix for all individual page titles, unless [`titleTemplate`](#titletemplate) is defined. An individual page's final title will be the text content of its first `<h1>` header, combined with the global `title` as the suffix. For example with the following config and page content:
```ts
export default {
title: 'My Awesome Site'
}
```
```md
# Hello
```
The title of the page will be `Hello | My Awesome Site`.
### titleTemplate
- Type: `string | boolean`
- Can be overridden per page via [frontmatter](./frontmatter-config#titletemplate)
Allows customizing each page's title suffix or the entire title. For example:
```ts
export default {
title: 'My Awesome Site',
titleTemplate: 'Custom Suffix'
}
```
```md
# Hello
```
The title of the page will be `Hello | Custom Suffix`.
To completely customize how the title should be rendered, you can use the `:title` symbol in `titleTemplate`:
```ts
export default {
titleTemplate: ':title - Custom Suffix'
}
```
Here `:title` will be replaced with the text inferred from the page's first `<h1>` header. The title of the previous example page will be `Hello - Custom Suffix`.
The option can be set to `false` to disable title suffixes.
### description
- Type: `string`
- Default: `A VitePress site`
- Can be overridden per page via [frontmatter](./frontmatter-config#description)
Description for the site. This will render as a `<meta>` tag in the page HTML.
```ts
export default {
description: 'A VitePress site'
}
```
### head
- Type: `HeadConfig[]`
- Default: `[]`
- Can be appended per page via [frontmatter](./frontmatter-config#head)
Additional elements to render in the `<head>` tag in the page HTML. The user-added tags are rendered before the closing `head` tag, after VitePress tags.
```ts
type HeadConfig =
| [string, Record<string, string>]
| [string, Record<string, string>, string]
```
#### Example: Adding a favicon
```ts
export default {
head: [['link', { rel: 'icon', href: '/favicon.ico' }]]
} // put favicon.ico in public directory, if base is set, use /base/favicon.ico
/* Would render:
<link rel="icon" href="/favicon.ico">
*/
```
#### Example: Adding Google Fonts
```ts
export default {
head: [
[
'link',
{ rel: 'preconnect', href: 'https://fonts.googleapis.com' }
],
[
'link',
{ rel: 'preconnect', href: 'https://fonts.gstatic.com', crossorigin: '' }
],
[
'link',
{ href: 'https://fonts.googleapis.com/css2?family=Roboto&display=swap', rel: 'stylesheet' }
]
]
}
/* Would render:
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Roboto&display=swap" rel="stylesheet">
*/
```
#### Example: Registering a service worker
```ts
export default {
head: [
[
'script',
{ id: 'register-sw' },
`;(() => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
}
})()`
]
]
}
/* Would render:
<script id="register-sw">
;(() => {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.register('/sw.js')
}
})()
</script>
*/
```
#### Example: Using Google Analytics
```ts
export default {
head: [
[
'script',
{ async: '', src: 'https://www.googletagmanager.com/gtag/js?id=TAG_ID' }
],
[
'script',
{},
`window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'TAG_ID');`
]
]
}
/* Would render:
<script async src="https://www.googletagmanager.com/gtag/js?id=TAG_ID"></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'TAG_ID');
</script>
*/
```
### lang
- Type: `string`
- Default: `en-US`
The lang attribute for the site. This will render as a `<html lang="en-US">` tag in the page HTML.
```ts
export default {
lang: 'en-US'
}
```
### base
- Type: `string`
- Default: `/`
The base URL the site will be deployed at. You will need to set this if you plan to deploy your site under a sub path, for example, GitHub pages. If you plan to deploy your site to `https://foo.github.io/bar/`, then you should set base to `'/bar/'`. It should always start and end with a slash.
The base is automatically prepended to all the URLs that start with / in other options, so you only need to specify it once.
```ts
export default {
base: '/base/'
}
```
## Routing
### cleanUrls
- Type: `boolean`
- Default: `false`
When set to `true`, VitePress will remove the trailing `.html` from URLs. Also see [Generating Clean URL](../guide/routing#generating-clean-url).
::: warning Server Support Required
Enabling this may require additional configuration on your hosting platform. For it to work, your server must be able to serve `/foo.html` when visiting `/foo` **without a redirect**.
:::
### rewrites
- Type: `Record<string, string>`
Defines custom directory &lt;-&gt; URL mappings. See [Routing: Route Rewrites](../guide/routing#route-rewrites) for more details.
```ts
export default {
rewrites: {
'source/:page': 'destination/:page'
}
}
```
## Build
### srcDir
- Type: `string`
- Default: `.`
The directory where your markdown pages are stored, relative to project root. Also see [Root and Source Directory](../guide/routing#root-and-source-directory).
```ts
export default {
srcDir: './src'
}
```
### srcExclude
- Type: `string[]`
- Default: `undefined`
A [glob pattern](https://github.com/mrmlnc/fast-glob#pattern-syntax) for matching markdown files that should be excluded as source content.
```ts
export default {
srcExclude: ['**/README.md', '**/TODO.md']
}
```
### outDir
- Type: `string`
- Default: `./.vitepress/dist`
The build output location for the site, relative to [project root](../guide/routing#root-and-source-directory).
```ts
export default {
outDir: '../public'
}
```
### assetsDir
- Type: `string`
- Default: `assets`
Specify the directory to nest generated assets under. The path should be inside [`outDir`](#outdir) and is resolved relative to it.
```ts
export default {
assetsDir: 'static'
}
```
### cacheDir
- Type: `string`
- Default: `./.vitepress/cache`
The directory for cache files, relative to [project root](../guide/routing#root-and-source-directory). See also: [cacheDir](https://vitejs.dev/config/shared-options.html#cachedir).
```ts
export default {
cacheDir: './.vitepress/.vite'
}
```
### ignoreDeadLinks
- Type: `boolean | 'localhostLinks' | (string | RegExp | ((link: string, source: string) => boolean))[]`
- Default: `false`
When set to `true`, VitePress will not fail builds due to dead links.
When set to `'localhostLinks'`, the build will fail on dead links, but won't check `localhost` links.
```ts
export default {
ignoreDeadLinks: true
}
```
It can also be an array of exact url string, regex patterns, or custom filter functions.
```ts
export default {
ignoreDeadLinks: [
// ignore exact url "/playground"
'/playground',
// ignore all localhost links
/^https?:\/\/localhost/,
// ignore all links include "/repl/""
/\/repl\//,
// custom function, ignore all links include "ignore"
(url) => {
return url.toLowerCase().includes('ignore')
}
]
}
```
### metaChunk <Badge type="warning" text="experimental" />
- Type: `boolean`
- Default: `false`
When set to `true`, extract pages metadata to a separate JavaScript chunk instead of inlining it in the initial HTML. This makes each page's HTML payload smaller and makes the pages metadata cacheable, thus reducing server bandwidth when you have many pages in the site.
### mpa <Badge type="warning" text="experimental" />
- Type: `boolean`
- Default: `false`
When set to `true`, the production app will be built in [MPA Mode](../guide/mpa-mode). MPA mode ships 0kb JavaScript by default, at the cost of disabling client-side navigation and requires explicit opt-in for interactivity.
## Theming
### appearance
- Type: `boolean | 'dark' | 'force-dark' | 'force-auto' | import('@vueuse/core').UseDarkOptions`
- Default: `true`
Whether to enable dark mode (by adding the `.dark` class to the `<html>` element).
- If the option is set to `true`, the default theme will be determined by the user's preferred color scheme.
- If the option is set to `dark`, the theme will be dark by default, unless the user manually toggles it.
- If the option is set to `false`, users will not be able to toggle the theme.
- If the option is set to `'force-dark'`, the theme will always be dark and users will not be able to toggle it.
- If the option is set to `'force-auto'`, the theme will always be determined by the user's preferred color scheme and users will not be able to toggle it.
This option injects an inline script that restores users settings from local storage using the `vitepress-theme-appearance` key. This ensures the `.dark` class is applied before the page is rendered to avoid flickering.
`appearance.initialValue` can only be `'dark' | undefined`. Refs or getters are not supported.
### lastUpdated
- Type: `boolean`
- Default: `false`
Whether to get the last updated timestamp for each page using Git. The timestamp will be included in each page's page data, accessible via [`useData`](./runtime-api#usedata).
When using the default theme, enabling this option will display each page's last updated time. You can customize the text via [`themeConfig.lastUpdatedText`](./default-theme-config#lastupdatedtext) option.
## Customization
### markdown
- Type: `MarkdownOption`
Configure Markdown parser options. VitePress uses [Markdown-it](https://github.com/markdown-it/markdown-it) as the parser, and [Shiki](https://github.com/shikijs/shiki) to highlight language syntax. Inside this option, you may pass various Markdown related options to fit your needs.
```js
export default {
markdown: {...}
}
```
Check the [type declaration and jsdocs](https://github.com/vuejs/vitepress/blob/main/src/node/markdown/markdown.ts) for all the options available.
### vite
- Type: `import('vite').UserConfig`
Pass raw [Vite Config](https://vitejs.dev/config/) to internal Vite dev server / bundler.
```js
export default {
vite: {
// Vite config options
}
}
```
### vue
- Type: `import('@vitejs/plugin-vue').Options`
Pass raw [`@vitejs/plugin-vue` options](https://github.com/vitejs/vite-plugin-vue/tree/main/packages/plugin-vue#options) to the internal plugin instance.
```js
export default {
vue: {
// @vitejs/plugin-vue options
}
}
```
## Build Hooks
VitePress build hooks allow you to add new functionality and behaviors to your website:
- Sitemap
- Search Indexing
- PWA
- Teleports
### buildEnd
- Type: `(siteConfig: SiteConfig) => Awaitable<void>`
`buildEnd` is a build CLI hook, it will run after build (SSG) finish but before VitePress CLI process exits.
```ts
export default {
async buildEnd(siteConfig) {
// ...
}
}
```
### postRender
- Type: `(context: SSGContext) => Awaitable<SSGContext | void>`
`postRender` is a build hook, called when SSG rendering is done. It will allow you to handle the teleports content during SSG.
```ts
export default {
async postRender(context) {
// ...
}
}
```
```ts
interface SSGContext {
content: string
teleports?: Record<string, string>
[key: string]: any
}
```
### transformHead
- Type: `(context: TransformContext) => Awaitable<HeadConfig[]>`
`transformHead` is a build hook to transform the head before generating each page. It will allow you to add head entries that cannot be statically added to your VitePress config. You only need to return extra entries, they will be merged automatically with the existing ones.
::: warning
Don't mutate anything inside the `context`.
:::
```ts
export default {
async transformHead(context) {
// ...
}
}
```
```ts
interface TransformContext {
page: string // e.g. index.md (relative to srcDir)
assets: string[] // all non-js/css assets as fully resolved public URL
siteConfig: SiteConfig
siteData: SiteData
pageData: PageData
title: string
description: string
head: HeadConfig[]
content: string
}
```
Note that this hook is only called when generating the site statically. It is not called during dev. If you need to add dynamic head entries during dev, you can use the [`transformPageData`](#transformpagedata) hook instead:
```ts
export default {
transformPageData(pageData) {
pageData.frontmatter.head ??= []
pageData.frontmatter.head.push([
'meta',
{
name: 'og:title',
content:
pageData.frontmatter.layout === 'home'
? `VitePress`
: `${pageData.title} | VitePress`
}
])
}
}
```
#### Example: Adding a canonical URL `<link>`
```ts
export default {
transformPageData(pageData) {
const canonicalUrl = `https://example.com/${pageData.relativePath}`
.replace(/index\.md$/, '')
.replace(/\.md$/, '.html')
pageData.frontmatter.head ??= []
pageData.frontmatter.head.push([
'link',
{ rel: 'canonical', href: canonicalUrl }
])
}
}
```
### transformHtml
- Type: `(code: string, id: string, context: TransformContext) => Awaitable<string | void>`
`transformHtml` is a build hook to transform the content of each page before saving to disk.
::: warning
Don't mutate anything inside the `context`. Also, modifying the html content may cause hydration problems in runtime.
:::
```ts
export default {
async transformHtml(code, id, context) {
// ...
}
}
```
### transformPageData
- Type: `(pageData: PageData, context: TransformPageContext) => Awaitable<Partial<PageData> | { [key: string]: any } | void>`
`transformPageData` is a hook to transform the `pageData` of each page. You can directly mutate `pageData` or return changed values which will be merged into the page data.
::: warning
Don't mutate anything inside the `context` and be careful that this might impact the performance of dev server, especially if you have some network requests or heavy computations (like generating images) in the hook. You can check for `process.env.NODE_ENV === 'production'` for conditional logic.
:::
```ts
export default {
async transformPageData(pageData, { siteConfig }) {
pageData.contributors = await getPageContributors(pageData.relativePath)
}
// or return data to be merged
async transformPageData(pageData, { siteConfig }) {
return {
contributors: await getPageContributors(pageData.relativePath)
}
}
}
```
```ts
interface TransformPageContext {
siteConfig: SiteConfig
}
```

@ -44,6 +44,10 @@
{
"label": "فارسی",
"lang": "fa"
},
{
"label": "日本語",
"lang": "ja"
}
],
"outDir": ".vitepress/dist/_translations",

Loading…
Cancel
Save