prepare new translation

pull/1593/head
Xavi Lee 4 years ago
parent 3dbbd80ec3
commit 8227cde90b

@ -1,10 +1,6 @@
import { createRequire } from 'module'
import { defineConfig } from 'vitepress'
import locales from './locales'
const require = createRequire(import.meta.url)
const pkg = require('vitepress/package.json')
export default defineConfig({
title: 'VitePress',
@ -12,7 +8,7 @@ export default defineConfig({
cleanUrls: true,
head: [['meta', { name: 'theme-color', content: '#3c8772' }]],
markdown: {
headers: {
level: [0, 0]

@ -11,12 +11,9 @@ export default defineConfig({
themeConfig: {
nav: nav(),
lastUpdatedText: 'last Updated',
sidebar: {
'/guide/': sidebarGuide(),
'/config/': sidebarConfig(),
'/api/': sidebarGuide()
'/reference/': sidebarReference()
},
editLink: {
@ -31,6 +28,17 @@ export default defineConfig({
footer: {
message: 'Released under the MIT License.',
copyright: 'Copyright © 2019-present Evan You'
},
algolia: {
appId: '8J64VVRP8K',
apiKey: 'a18e2f4cc5665f6602c5631fd868adfd',
indexName: 'vitepress'
},
carbonAds: {
code: 'CEBDT27Y',
placement: 'vuejsorg'
}
}
})
@ -39,14 +47,9 @@ function nav() {
return [
{ text: 'Guide', link: '/guide/what-is-vitepress', activeMatch: '/guide/' },
{
text: 'Config Reference',
link: '/config/introduction',
activeMatch: '/config/'
},
{
text: 'Runtime API',
link: '/api/',
activeMatch: '/api/'
text: 'Reference',
link: '/reference/site-config',
activeMatch: '/reference/'
},
{
text: pkg.version,
@ -72,9 +75,8 @@ function sidebarGuide() {
items: [
{ text: 'What is VitePress?', link: '/guide/what-is-vitepress' },
{ text: 'Getting Started', link: '/guide/getting-started' },
{ text: 'Configuration', link: '/guide/configuration' },
{ text: 'Routing', link: '/guide/routing' },
{ text: 'Deploying', link: '/guide/deploying' }
{ text: 'Deploy', link: '/guide/deploy' }
]
},
{
@ -92,45 +94,112 @@ function sidebarGuide() {
text: 'Customization',
collapsed: false,
items: [
{ text: 'Default Theme', link: '/guide/default-theme' },
{ text: 'Using a Custom Theme', link: '/guide/custom-theme' },
{
text: 'Extending the Default Theme',
link: '/guide/customization-extending-default-theme'
link: '/guide/extending-default-theme'
},
{ text: 'Building a Custom Theme', link: '/guide/customization-intro' },
{
text: 'Runtime API',
link: '/api/'
},
{ text: 'Build-Time Data Loading', link: '/guide/data-loading' }
{ text: 'Build-Time Data Loading', link: '/guide/data-loading' },
{ text: 'Connecting to a CMS', link: '/guide/cms' }
]
},
{
text: 'Migrations',
text: 'Experimental',
collapsed: false,
items: [
{
text: 'Migration from VuePress',
link: '/guide/migration-from-vuepress'
},
{
text: 'Migration from VitePress 0.x',
link: '/guide/migration-from-vitepress-0'
text: 'MPA Mode',
link: '/guide/mpa-mode'
}
]
},
// {
// text: 'Migrations',
// collapsed: false,
// items: [
// {
// text: 'Migration from VuePress',
// link: '/guide/migration-from-vuepress'
// },
// {
// text: 'Migration from VitePress 0.x',
// link: '/guide/migration-from-vitepress-0'
// }
// ]
// },
{
text: 'Config & API Reference',
link: '/reference/site-config'
}
]
}
function sidebarConfig() {
function sidebarReference() {
return [
{
text: 'Config Reference',
text: 'Reference',
items: [
{ text: 'Introduction', link: '/config/introduction' },
{ text: 'App Config', link: '/config/app-config' },
{ text: 'Default Theme Config', link: '/config/theme-config' },
{ text: 'Frontmatter Config', link: '/config/frontmatter-config' }
{ text: 'Site Config', link: '/reference/site-config' },
{ text: 'Frontmatter Config', link: '/reference/frontmatter-config' },
{ text: 'Runtime API', link: '/reference/runtime-api' },
{ text: 'CLI', link: '/reference/cli' },
{
text: 'Default Theme',
items: [
{
text: 'Overview',
link: '/reference/default-theme-config'
},
{
text: 'Nav',
link: '/reference/default-theme-nav'
},
{
text: 'Sidebar',
link: '/reference/default-theme-sidebar'
},
{
text: 'Home Page',
link: '/reference/default-theme-home-page'
},
{
text: 'Footer',
link: '/reference/default-theme-footer'
},
{
text: 'Layout',
link: '/reference/default-theme-layout'
},
{
text: 'Badge',
link: '/reference/default-theme-badge'
},
{
text: 'Team Page',
link: '/reference/default-theme-team-page'
},
{
text: 'Prev / Next Links',
link: '/reference/default-theme-prev-next-links'
},
{
text: 'Edit Link',
link: '/reference/default-theme-edit-link'
},
{
text: 'Last Updated Timestamp',
link: '/reference/default-theme-last-updated'
},
{
text: 'Algolia Search',
link: '/reference/default-theme-search'
},
{
text: 'Carbon Ads',
link: '/reference/default-theme-carbon-ads'
}
]
}
]
}
]

@ -17,8 +17,7 @@ export default defineConfig({
sidebar: {
'/zh/guide/': sidebarGuide(),
'/zh/config/': sidebarConfig(),
'/zh/api/': sidebarGuide()
'/zh/reference/': sidebarReference()
},
editLink: {
@ -33,6 +32,17 @@ export default defineConfig({
footer: {
message: 'Released under the MIT License.',
copyright: 'Copyright © 2019-present Evan You'
},
algolia: {
appId: '8J64VVRP8K',
apiKey: 'a18e2f4cc5665f6602c5631fd868adfd',
indexName: 'vitepress'
},
carbonAds: {
code: 'CEBDT27Y',
placement: 'vuejsorg'
}
}
})
@ -40,19 +50,14 @@ export default defineConfig({
function nav() {
return [
{
text: '指南',
text: 'Guide',
link: '/zh/guide/what-is-vitepress',
activeMatch: '/zh/guide/'
},
{
text: '运行时 API',
link: '/zh/api/',
activeMatch: '/zh/api/'
},
{
text: '配置参考',
link: '/zh/config/introduction',
activeMatch: '/zh/config/'
text: '参考',
link: '/zh/reference/site-config',
activeMatch: '/zh/reference/'
},
{
text: pkg.version,
@ -74,88 +79,138 @@ function sidebarGuide() {
return [
{
text: '简介',
collapsed: true,
collapsed: false,
items: [
{ text: 'VitePress 是什么', link: '/zh/guide/what-is-vitepress' },
{ text: ' VitePress 是什么', link: '/zh/guide/what-is-vitepress' },
{ text: '快速开始', link: '/zh/guide/getting-started' },
{ text: '配置', link: '/zh/guide/configuration' },
{ text: '路由', link: '/zh/guide/routing' },
{ text: '部署', link: '/zh/guide/deploying' }
{ text: '部署', link: '/zh/guide/deploy' }
]
},
{
text: '写作',
collapsed: true,
collapsed: false,
items: [
{ text: 'Markdown 扩展', link: '/zh/guide/markdown' },
{ text: '资源处理', link: '/zh/guide/asset-handling' },
{ text: 'Markdown Extensions', link: '/zh/guide/markdown' },
{ text: 'Asset Handling', link: '/zh/guide/asset-handling' },
{ text: 'Frontmatter', link: '/zh/guide/frontmatter' },
{ text: '在 Markdown 中使用 Vue', link: '/zh/guide/using-vue' },
{ text: '国际化', link: '/zh/guide/i18n' }
]
},
{
text: '主题',
collapsed: true,
items: [
{ text: '简介', link: '/zh/guide/customization-intro' },
{ text: '导航', link: '/zh/guide/theme-nav' },
{ text: '侧边栏', link: '/zh/guide/theme-sidebar' },
{ text: '上下页链接', link: '/zh/guide/theme-prev-next-link' },
{ text: '编辑链接', link: '/zh/guide/theme-edit-link' },
{ text: '最后更新', link: '/zh/guide/theme-last-updated' },
{ text: '布局', link: '/zh/guide/theme-layout' },
{ text: '主页', link: '/zh/guide/theme-home-page' },
{ text: '团队页', link: '/zh/guide/theme-team-page' },
{ text: '徽章', link: '/zh/guide/theme-badge' },
{ text: '页脚', link: '/zh/guide/theme-footer' },
{ text: '搜索', link: '/zh/guide/theme-search' },
{ text: 'Carbon Ads', link: '/zh/guide/theme-carbon-ads' }
{ text: 'Using Vue in Markdown', link: '/zh/guide/using-vue' },
{ text: 'Internationalization', link: '/zh/guide/i18n' }
]
},
{
text: '迁移',
collapsed: true,
text: 'Customization',
collapsed: false,
items: [
{ text: 'Using a Custom Theme', link: '/zh/guide/custom-theme' },
{
text: '从 VuePress 迁移',
link: '/zh/guide/migration-from-vuepress'
text: 'Extending the Default Theme',
link: '/zh/guide/extending-default-theme'
},
{
text: '从 VitePress 0.x 迁移',
link: '/zh/guide/migration-from-vitepress-0'
}
{ text: 'Build-Time Data Loading', link: '/zh/guide/data-loading' },
{ text: 'Connecting to a CMS', link: '/zh/guide/cms' }
]
},
{
text: '自定义',
text: 'Experimental',
collapsed: false,
items: [
{ text: '默认主题', link: '/zh/guide/default-theme' },
{
text: '扩展默认主题',
link: '/zh/guide/customization-extending-default-theme'
},
{ text: '构建自定义主题', link: '/zh/guide/customization-intro' },
{
text: '运行时 API',
link: '/zh/api/'
},
{ text: 'Build-Time Data Loading', link: '/zh/guide/data-loading' }
text: 'MPA Mode',
link: '/zh/guide/mpa-mode'
}
]
},
// {
// text: 'Migrations',
// collapsed: false,
// items: [
// {
// text: 'Migration from VuePress',
// link: '/zh/guide/migration-from-vuepress'
// },
// {
// text: 'Migration from VitePress 0.x',
// link: '/zh/guide/migration-from-vitepress-0'
// }
// ]
// },
{
text: 'Config & API Reference',
link: '/zh/reference/site-config'
}
]
}
function sidebarConfig() {
function sidebarReference() {
return [
{
text: '配置参考',
text: 'Reference',
items: [
{ text: '简介', link: '/zh/config/introduction' },
{ text: '应用全局配置', link: '/zh/config/app-config' },
{ text: '主题配置', link: '/zh/config/theme-config' },
{ text: 'Frontmatter 配置', link: '/zh/config/frontmatter-config' }
{ text: 'Site Config', link: '/zh/reference/site-config' },
{
text: 'Frontmatter Config',
link: '/zh/reference/frontmatter-config'
},
{ text: 'Runtime API', link: '/zh/reference/runtime-api' },
{ text: 'CLI', link: '/zh/reference/cli' },
{
text: 'Default Theme',
items: [
{
text: 'Overview',
link: '/zh/reference/default-theme-config'
},
{
text: 'Nav',
link: '/zh/reference/default-theme-nav'
},
{
text: 'Sidebar',
link: '/zh/reference/default-theme-sidebar'
},
{
text: 'Home Page',
link: '/zh/reference/default-theme-home-page'
},
{
text: 'Footer',
link: '/zh/reference/default-theme-footer'
},
{
text: 'Layout',
link: '/zh/reference/default-theme-layout'
},
{
text: 'Badge',
link: '/zh/reference/default-theme-badge'
},
{
text: 'Team Page',
link: '/zh/reference/default-theme-team-page'
},
{
text: 'Prev / Next Links',
link: '/zh/reference/default-theme-prev-next-links'
},
{
text: 'Edit Link',
link: '/zh/reference/default-theme-edit-link'
},
{
text: 'Last Updated Timestamp',
link: '/zh/reference/default-theme-last-updated'
},
{
text: 'Algolia Search',
link: '/zh/reference/default-theme-search'
},
{
text: 'Carbon Ads',
link: '/zh/reference/default-theme-carbon-ads'
}
]
}
]
}
]

@ -1,94 +0,0 @@
# 运行时 API 参考 {#runtime-api-reference}
VitePress 提供了几个内置 API 来获取数据。VitePress 还提供了一些可以全局使用的内置组件。
可以从 `vitepress` 全局引入辅助函数,通常用于自定义主题 Vue 组件。当然,它们也可以在 .md 页面中使用,因为 Markdown 文件会被编译成 Vue 单文件组件。
`use*` 开头的方法表示它是一个 [Vue 3 组合式 API](https://cn.vuejs.org/guide/introduction.html#composition-api) 函数,只能在 `setup()` 内部使用或者使用 `<script setup>`
## `useData`
返回页面的属性数据,返回的对象具有以下类型:
```ts
interface VitePressData<T = any> {
site: Ref<SiteData<T>>
page: Ref<PageData>
theme: Ref<T> // themeConfig from .vitepress/config.js
frontmatter: Ref<PageData['frontmatter']>
title: Ref<string>
description: Ref<string>
lang: Ref<string>
isDark: Ref<boolean>
dir: Ref<string>
localeIndex: Ref<string>
}
```
**例子:**
```vue
<script setup>
import { useData } from 'vitepress'
const { theme } = useData()
</script>
<template>
<h1>{{ theme.footer.copyright }}</h1>
</template>
```
## `useRoute`
返回具有以下类型的当前路由对象:
```ts
interface Route {
path: string
data: PageData
component: Component | null
}
```
## `useRouter`
返回 VitePress 路由实例,用来以编程方式导航到另一个页面。
```ts
interface Router {
route: Route
go: (href?: string) => Promise<void>
}
```
## `withBase`
- **Type**: `(path: string) => string`
将配置的 [`base`](/config/app-config#base) 添加到给定的 URL 路径。另请参阅 [Base URL](/guide/asset-handling#base-url)。
## `<Content />`
`<Content />` 组件显示渲染的 markdown 内容。这在[创建你自己的主题时](/guide/customization-intro)很有用。
```vue
<template>
<h1>Custom Layout!</h1>
<Content />
</template>
```
## `<ClientOnly />`
`<ClientOnly />` 组件只在客户端渲染它的插槽。
由于 VitePress 应用在生成静态文件之后会在 Node.js 中进行服务端渲染,因此任何 Vue 的使用都必须符合通用代码的要求。简而言之,确保只在 beforeMount 或 mounted 钩子中访问浏览器以及 DOM API。
如果你正在使用不支持 SSR 的组件 (例如,包含自定义指令),你可以将它们包装在 `ClientOnly` 组件中。
```vue-html
<ClientOnly>
<NonSSRFriendlyComponent />
</ClientOnly>
```

@ -1,393 +0,0 @@
# 应用全局配置 {#app-config}
应用全局配置是定义站点的全局配置的地方。应用全局配置不仅限于主题配置,还有如“根目录”的配置,或站点的“标题”设置。
```ts
export default {
// These are app level configs.
lang: 'en-US',
title: 'VitePress',
description: 'Vite & Vue powered static site generator.',
...
}
```
## appearance
- 类型:`boolean | 'dark'`
- 默认值:`true`
这个配置项可以配置是否开启“黑暗”模式。
- 如果选项设置为 `true`,默认的主题将由用户的首选的颜色方案来决定。
- 如果选项设置为 `dark`,该主题将默认为深色,用户手动切换颜色才会发生改变。
- 如果选项设置为 `false`,用户将无法切换主题。
它还注入了内联脚本,通过 `vitepress-theme-appearance` 键从本地存储中读取用户设置,并恢复用户偏好的颜色模式。
```ts
export default {
appearance: true
}
```
## base
- 类型:`string`
- 默认值:`/`
站点将被部署到的根 URL。如果你打算在一个子路径下部署你的站点例如 GitHub 页面,你就需要进行配置。如果你计划将站点部署到 `https://foo.github.io/bar/`,那么你应该将 base 设置为 `'/bar/'`。它应该总是以斜线开始,以斜线结束。
base 会自动预置到其他选项中以/开头的所有 URL 中,所以你只需要指定一次。
```ts
export default {
base: '/base/'
}
```
## description
- 类型:`string`
- 默认值:`A VitePress site`
站点的描述。在 HTML 页面中将被渲染成 `<meta>` 标签。
```ts
export default {
description: 'A VitePress site'
}
```
## head
- 类型:`HeadConfig[]`
- 默认值:`[]`
在 HTML 页面的 `<head>` 标签中呈现的额外元素。用户添加的标签将在 `head` 标签结束前呈现,在 VitePress 标签之后。
```ts
export default {
head: [
[
'link',
{ rel: 'preconnect', href: 'https://fonts.gstatic.com', crossorigin: '' }
]
// would render: <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
]
}
```
```ts
type HeadConfig =
| [string, Record<string, string>]
| [string, Record<string, string>, string]
```
## ignoreDeadLinks
- 类型:`boolean | 'localhostLinks'`
- 默认值:`false`
当将其设置为 `true`VitePress 不会因为死链接构建失败。若将其设置为 `localhostLinks``localhost` 链接不会构建失败,其他的死链接仍然会使构建失败。
```ts
export default {
ignoreDeadLinks: true
}
```
## lang
- 类型:`string`
- 默认值:`en-US`
站点的语言属性。在 HTML 页面中将被渲染为 `<html lang="en-US">` 标签。
```ts
export default {
lang: 'en-US'
}
```
## lastUpdated
- 类型:`boolean`
- 默认值:`false`
使用 git commit 来获取时间戳。该选项使默认主题显示页面的最后更新时间。你可以通过 [`themeConfig.lastUpdatedText`](theme-config#lastupdatedtext) 选项来自定义文本。
```ts
export default {
lastUpdated: true
}
```
## markdown
- 类型:`MarkdownOption`
配置 Markdown 解析器的选项。VitePress 使用 [Markdown-it](https://github.com/markdown-it/markdown-it) 作为解析器,并使用 [Shiki](https://shiki.matsu.io/) 来高亮语言的语法。在这个选项中,你可以通过各种与 Markdown 有关的选项来满足你的需要。
```js
export default {
markdown: {
theme: 'material-palenight',
lineNumbers: true
}
}
```
以下是你在这个对象中可以进行设置的所有选项:
```ts
interface MarkdownOptions extends MarkdownIt.Options {
// Custom theme for syntax highlighting.
// You can use an existing theme.
// See: https://github.com/shikijs/shiki/blob/main/docs/themes.md#all-themes
// Or add your own theme.
// See: https://github.com/shikijs/shiki/blob/main/docs/themes.md#loading-theme
theme?:
| Shiki.IThemeRegistration
| { light: Shiki.IThemeRegistration; dark: Shiki.IThemeRegistration }
// Enable line numbers in code block.
lineNumbers?: boolean
// Add support for your own languages.
// https://github.com/shikijs/shiki/blob/main/docs/languages.md#supporting-your-own-languages-with-shiki
languages?: Shiki.ILanguageRegistration
// markdown-it-anchor plugin options.
// See: https://github.com/valeriangalliat/markdown-it-anchor#usage
anchor?: anchorPlugin.AnchorOptions
// markdown-it-attrs plugin options.
// See: https://github.com/arve0/markdown-it-attrs
attrs?: {
leftDelimiter?: string
rightDelimiter?: string
allowedAttributes?: string[]
disable?: boolean
}
// specify default language for syntax highlighter
defaultHighlightLang?: string
// @mdit-vue/plugin-frontmatter plugin options.
// See: https://github.com/mdit-vue/mdit-vue/tree/main/packages/plugin-frontmatter#options
frontmatter?: FrontmatterPluginOptions
// @mdit-vue/plugin-headers plugin options.
// See: https://github.com/mdit-vue/mdit-vue/tree/main/packages/plugin-headers#options
headers?: HeadersPluginOptions
// @mdit-vue/plugin-sfc plugin options.
// See: https://github.com/mdit-vue/mdit-vue/tree/main/packages/plugin-sfc#options
sfc?: SfcPluginOptions
// @mdit-vue/plugin-toc plugin options.
// See: https://github.com/mdit-vue/mdit-vue/tree/main/packages/plugin-toc#options
toc?: TocPluginOptions
// Configure the Markdown-it instance.
config?: (md: MarkdownIt) => void
}
```
## outDir
- 类型:`string`
- 默认值:`./.vitepress/dist`
站点的构建输出位置,相对于项目根目录。(比如相对于 `docs` 目录,如果你运行的是 `vitepress build docs`)。
```ts
export default {
outDir: '../public'
}
```
## cacheDir
- 类型:`string`
- 默认值:`./.vitepress/cache`
缓存文件的目录,相对于项目根目录。(比如相对于 `docs` 目录,如果你运行的是 `vitepress build docs`)。参见:[cacheDir](https://cn.vitejs.dev/config/shared-options.html#cachedir)。
```ts
export default {
cacheDir: './.vitepress/.vite'
}
```
## srcDir
- 类型:`string`
- 默认值:`.`
存储 markdown 文件的位置,相对于项目根目录。
```ts
export default {
srcDir: './src'
}
```
## title
- 类型:`string`
- 默认值:`VitePress`
站点的标题。这将显示在导航栏中。除非定义了 `titleTemplate`,否则也作为所有页面标题的后缀。
```ts
export default {
title: 'VitePress'
}
```
## titleTemplate
- 类型:`string | boolean`
标题的后缀。例如,如果你将 `title` 设置为 `VitePress`,并将 `titleTemplate` 设置为 `My Site`那么html 标题就变成 `VitePress | My Site`
设置为 `false` 表示禁用该功能。如果该选项是 `undefined`,那么将使用 `title` 选项的值。
```ts
export default {
title: 'VitePress',
titleTemplate: 'Vite & Vue powered static site generator'
}
```
要配置 `|` 以外的标题分隔符,你可以省略 `title`,在 `titleTemplate` 中使用 `:title` 符号。
```ts
export default {
titleTemplate: ':title - Vitepress'
}
```
## cleanUrls {#cleanurls}
- 类型:`boolean`
- 默认值:`false`
允许从 URL 中去除尾部的 `.html`,并可选择生成简洁的目录结构。
```ts
export default {
cleanUrls: true
}
```
::: warning
启用此功能可能需要在你的托管平台上进行额外配置。为了使其正常工作,你的服务器必须**在不重定向的情况下**,请求 `/foo` 时提供 `/foo.html`
:::
## rewrites
- Type: `Record<string, string>`
定义自定义目录和 URL 的映射。有关详细信息,请参阅[路由:自定义映射](/guide/routing#customize-the-mappings)。
```ts
export default {
rewrites: {
'source/:page': 'destination/:page'
}
}
```
## 构建钩子 {#build-hooks}
VitePress 构建钩子允许你向你的网站添加新的功能和行为:
- Sitemap
- Search Indexing
- PWA
### transformHead
- 类型:`(ctx: TransformContext) => Awaitable<HeadConfig[]>`
`transformHead` 是一个构建钩子,用于在生成每个页面之前转换 head。它将允许你添加不能静态添加到你的VitePress 配置中的 head 选项。你只需要返回额外的选项,它们将被自动合并到现有的选项中。
::: warning
不要改变 `ctx` 中的任何东西。
:::
```ts
export default {
async transformHead(ctx) {
// ...
}
}
```
```ts
interface TransformContext {
siteConfig: SiteConfig
siteData: SiteData
pageData: PageData
title: string
description: string
head: HeadConfig[]
content: string
}
```
### transformHtml
- 类型:`(code: string, id: string, ctx: TransformContext) => Awaitable<string | void>`
`transformHtml` 是一个构建钩子,用于在保存到磁盘之前转换每个页面的内容。
::: warning
不要改变 `ctx` 中的任何东西。另外,修改 html 内容可能会在运行时引起激活问题。
:::
```ts
export default {
async transformHtml(code, id, context) {
// ...
}
}
```
### transformPageData
- 类型:`(pageData: PageData) => Awaitable<Partial<PageData> | { [key: string]: any } | void>`
`transformPageData` 是一个用于转换每个页面的 `pageData` 的钩子。你可以直接改变 `pageData` 或者返回改变的值,这些值将被合并到 PageData 中。
```ts
export default {
async transformPageData(pageData) {
pageData.contributors = await getPageContributors(pageData.relativePath)
}
// or return data to be merged
async transformPageData(pageData) {
return {
contributors: await getPageContributors(pageData.relativePath)
}
}
}
```
### buildEnd
- 类型:`(siteConfig: SiteConfig) => Awaitable<void>`
`buildEnd` 是一个构建 CLI 的钩子,它将在构建 (SSG) 完成后VitePress CLI 进程退出前运行。
```ts
export default {
async buildEnd(siteConfig) {
// ...
}
}
```

@ -1,192 +0,0 @@
# Frontmatter 配置 {#frontmatter-config}
Frontmatter 支持基于页面的配置。在每个标签上,你可以自由地添加任何设置来覆盖任何全局应用或主题配置。此外,还有一些配置,你只能在 Frontmatter 中定义。
```yaml
---
title: Docs with VitePress
editLink: true
---
```
你可以通过 `$frontmatter` 在任何 markdown 文件中访问 frontmatter。
```md
{{ $frontmatter.title }}
```
## title
- Type: `string`
页面的标题。它与 [config.title](../config/app-config#title) 相同,并覆盖了应用全局配置。
```yaml
---
title: VitePress
---
```
## titleTemplate
- Type: `string | boolean`
标题的后缀。它与 [config.titleTemplate](../config/app-config#titletemplate) 相同,并覆盖了应用全局配置。
```yaml
---
title: VitePress
titleTemplate: Vite & Vue powered static site generator
---
```
## description
- Type: `string`
页面的描述。它与 [config.description](../config/app-config#description) 相同,并覆盖了应用全局配置。
```yaml
---
description: VitePress
---
```
## head
- Type: `HeadConfig[]`
指定要注入的额外 head 标签。
```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]
```
## lastUpdated
- Type: `boolean`
- Default: `true`
在当前页面是否显示[最后更新](../guide/theme-last-updated)文本。
```yaml
---
lastUpdated: false
---
```
## layout
- Type: `doc | home | page`
- Default: `doc`
决定页面的布局。
- `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
- Type: `Hero`
This option only takes effect when `layout` is set to `home`.
It defines contents of home hero section.
```yaml
---
layout: home
hero:
name: VitePress
text: Vite & Vue powered static site generator.
tagline: Lorem ipsum...
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
// Action buttons to display in home hero section.
actions?: HeroAction[]
}
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
}
```
## features
- Type: `Feature[]`
This option only takes effect when `layout` is set to `home`.
It defines items to display in features section.
You may learn more about it in [Theme: Home Page](../guide/theme-home-page).
## aside
- Type: `boolean`
- Default: `true`
If you want the right aside component in `doc` layout not to be shown, set this option to `false`.
```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](../config/theme-config#outline), and it overrides the theme config.

@ -1,76 +0,0 @@
# 简介 {#introduction}
将配置文件放在 `.vitepress/config.js` 中。 这是放置所有 VitePress 特定文件的地方。
```
.
├─ docs
│ ├─ .vitepress
│ │ └─ config.js
│ └─ index.md
└─ package.json
```
::: tip 提示
你也可以使用任意的 `.ts`、`.cjs`、`.mjs`、`.cts` 和 `.mts` 作为配置文件的扩展名。
:::
VitePress 带有 2 种类型的配置。一种是[应用全局配置](./app-config),它配置站点的基本功能,例如设置站点的标题,或自定义 Markdown 解析器的工作方式。其次是[主题配置](./theme-config),用于配置站点的主题,例如添加侧边栏,或者添加“在 GitHub 上编辑此页面”链接等功能。
你还可以在 [Frontmatter](./frontmatter-config) 中进行另一种配置。Frontmatter 配置可以覆盖在该特定页面的应用全局配置或主题配置上定义的全局配置。但是,有几个选项也仅在 frontmatter 中可用。
请参阅相应的配置页面以了解更多信息。
## 配置智能提示 {#config-intellisense}
由于 VitePress 附带 TypeScript 类型,你可以利用 IDE 的智能提示和 jsdoc 类型提示:
```js
/**
* @type {import('vitepress').UserConfig}
*/
const config = {
// ...
}
export default config
```
或者,你可以使用 `defineConfig` 辅助函数,它会提供智能提示,而无需 jsdoc 注释:
```js
import { defineConfig } from 'vitepress'
export default defineConfig({
// ...
})
```
VitePress 也直接支持 TS 配置文件。 你也可以将 `.vitepress/config.ts``defineConfig` 辅助函数一起使用。
## 主题配置类型 {#typed-theme-config}
默认情况下,`defineConfig` 辅助函数使用默认主题的主题配置类型:
```ts
import { defineConfig } from 'vitepress'
export default defineConfig({
themeConfig: {
// Type is `DefaultTheme.Config`
}
})
```
如果你使用自定义主题并希望对主题配置进行类型检查,则需要使用 `defineConfigWithTheme`,并通过通用参数传递自定义主题的配置类型:
```ts
import { defineConfigWithTheme } from 'vitepress'
import { ThemeConfig } from 'your-theme'
export default defineConfigWithTheme<ThemeConfig>({
themeConfig: {
// Type is `ThemeConfig`
}
})
```

@ -1,46 +1,51 @@
# 资源处理 {#asset-handling}
# Asset Handling
所有的 Markdown 文件都编译成 Vue 组件并由 [Vite](https://github.com/vitejs/vite) 处理。你可以**并且应该**使用相对路径引用资源:
All Markdown files are compiled into Vue components and processed by [Vite](https://vitejs.dev/guide/assets.html). You can, **and should**, reference any assets using relative URLs:
```md
![一张图片](./image.png)
![An image](./image.png)
```
你可以在 markdown 文件、主题中的 `*.vue` 组件、styles 里和纯 `.css` 文件中通过使用绝对路径 (基于项目根目录) 或相对路径 (基于你的文件系统) 引用静态资源。相对路径的方式类似于使用 `vue-cli` 或 webpack 的 `file-loader` 时所习惯的写法。
You can reference static assets in your markdown files, your `*.vue` components in the theme, styles and plain `.css` files either using absolute public paths (based on project root) or relative paths (based on your file system). The latter is similar to the behavior you are used to if you have used Vite, Vue CLI, or webpack's `file-loader`.
常规的图片、媒体和字体文件类型会被自动检测为静态资源。
Common image, media, and font filetypes are detected and included as assets automatically.
所有引用的资源,包括使用绝对路径的资源,都将被复制到 dist 文件夹中,并在生产打包后生成哈希文件名。但不会复制未引用的资源。与 `vue-cli` 一样,小于 4kb 的图片资源将编译成 base64 的内联样式。
All referenced assets, including those using absolute paths, will be copied to the dist folder with a hashed file name in the production build. Never-referenced assets will not be copied. Image assets smaller than 4kb will be base64 inlined - this can be configured via the [`vite`](/reference/site-config#vite) config option.
所有资源路径的引用,包括绝对路径,都应基于你的工作目录结构。
All **static** path references, including absolute paths, should be based on your working directory structure.
## Public 文件 {#public-files}
## Public Files
有时你可能需要提供一些 Markdown 或主题组件中未直接引用的静态资源 (例如,站点图标和 PWA 图标)。 项目根目录下的 `public` 目录 (如果你正在运行的是 `vitepress build docs`,则为 `docs` 文件夹) 将会保留,用以提供源代码中从未引用的静态资源 (例如 `robots.txt`) 和需要保留完全相同的文件名 (不生成哈希) 的资源。
Sometimes you may need to provide static assets that are not directly referenced in any of your Markdown or theme components (for example, favicons and PWA icons). The `public` directory under project root (`docs` folder if you're running `vitepress build docs`) can be used as an escape hatch to provide static assets that either are never referenced in source code (e.g. `robots.txt`), or must retain the exact same file name (without hashing).
放在 `public` 中的资源将会直接复制到 dist 的根目录。
Assets placed in `public` will be copied to the root of the dist directory as-is.
注意,你应该使用从根目录开始以绝对路径引用放在 `public` 中的文件——例如,`public/icon.png` 在源代码中应始终引用为 `/icon.png`
Note that you should reference files placed in `public` using root absolute path - for example, `public/icon.png` should always be referenced in source code as `/icon.png`.
There is one exception to this: if you have an HTML page in `public` and link to it from the main site, the router will yield a 404 by default. To get around this, VitePress provides a `pathname://` protocol which allows you to link to another page in the same domain as if the link is external. Contrast these two links:
- [/pure.html](/pure.html)
- <pathname:///pure.html>
## Base URL
如果你的站点没有部署到根 URL则需要在 `.vitepress/config.js` 中设置 `base` 选项。 例如,如果你要将站点部署到 `https://foo.github.io/bar/`,那么 `base` 应该设置为 `'/bar/'` (以斜线开头和结尾)。
If your site is deployed to a non-root URL, you will need to set the `base` option in `.vitepress/config.js`. For example, if you plan to deploy your site to `https://foo.github.io/bar/`, then `base` should be set to `'/bar/'` (it should always start and end with a slash).
所有静态资源路径都会自动处理以适配不同的 `base` 配置值。例如,在 markdown 中对 `public` 下的资源使用绝对路径引用:
All your static asset paths are automatically processed to adjust for different `base` config values. For example, if you have an absolute reference to an asset under `public` in your markdown:
```md
![一张照片](/image-inside-public.png)
![An image](/image-inside-public.png)
```
使用这种引用方式,当你更改 `base` 配置值时无需再做修改。
You do **not** need to update it when you change the `base` config value in this case.
但是,如果你正在创作一个动态链接到资源的主题组件,例如图片的 `src` 是基于主题设置的:
However, if you are authoring a theme component that links to assets dynamically, e.g. an image whose `src` is based on a theme config value:
```vue
<img :src="theme.logoPath" />
```
在这种情况下,建议使用 VitePress 提供的 [`withBase` 辅助函数](/api/#withbase) 来引用静态资源:
In this case it is recommended to wrap the path with the [`withBase` helper](/reference/runtime-api#withbase) provided by VitePress:
```vue
<script setup>

@ -0,0 +1,56 @@
---
outline: deep
---
# Connecting to a CMS
## General Workflow
Connecting VitePress to a CMS will largely revolve around [Dynamic Routes](/guide/routing#dynamic-routes). Make sure to understand how it works before proceeding.
Since each CMS will work differently, here we can only provide a generic workflow that you will need to adapt to your specific scenario.
1. If your CMS requires authentication, create an `.env` file to store your API tokens and load it so:
```js
// posts/[id].paths.js
import { loadEnv } from 'vitepress'
const env = loadEnv('', process.cwd())
```
2. Fetch the necessary data from the CMS and format it into proper paths data:
```js
export default {
async paths() {
// use respective CMS client library if needed
const data = await (await fetch('https://my-cms-api', {
headers: {
// token if necessary
}
})).json()
return data.map(entry => {
return {
params: { id: entry.id, /* title, authors, date etc. */ },
content: entry.content
}
})
}
}
```
3. Render the content in the page:
```md
# {{ $params.title }}
- by {{ $params.author }} on {{ $params.date }}
<!-- @content -->
```
## Integration Guides
If you have written a guide on integrating VitePress with a specific CMS, please use the "Edit this page" link below to submit it here!

@ -1,27 +0,0 @@
# 配置 {#configuration}
当没有任何配置的时候,页面将非常轻量,但用户也无法通过导航去访问站点。要自定义站点,首先在 docs 目录里创建一个 `.vitepress` 目录。 这是放置所有 VitePress 特定文件的地方。 这时候你的项目结构大概是这样的:
```
.
├─ docs
│ ├─ .vitepress
│ │ └─ config.js
│ └─ index.md
└─ package.json
```
配置 VitePress 站点的基本文件是 `.vitepress/config.js`,它应该导出一个 JavaScript 对象:
```js
export default {
title: 'VitePress',
description: 'Just playing around.'
}
```
在上面的示例中,该站点使用 `VitePress` 作为标题,`Just play around.` 作为站点的描述。
在[主题:介绍](./customization-intro)里了解有关 VitePress 功能特性,以了解如何在此配置文件中配置特定功能。
你还可以在[配置](../config/introduction)中找到所有配置项。

@ -0,0 +1,222 @@
# Using a Custom Theme
## Theme Resolving
You can enable a custom theme by creating a `.vitepress/theme/index.js` or `.vitepress/theme/index.ts` file (the "theme entry file"):
```
.
├─ docs # project root
│ ├─ .vitepress
│ │ ├─ theme
│ │ │ └─ index.js # theme entry
│ │ └─ config.js # config file
│ └─ index.md
└─ package.json
```
VitePress will always use the custom theme instead of the default theme when it detects presence of a theme entry file. You can, however, [extend the default theme](./extending-default-theme) to perform advanced customizations on top of it.
## Theme Interface
A VitePress custom theme is defined as an object with the following interface:
```ts
interface Theme {
/**
* Root layout component for every page
* @required
*/
Layout: Component
/**
* Enhance Vue app instance
* @optional
*/
enhanceApp?: (ctx: EnhanceAppContext) => Awaitable<void>
/**
* Extend another theme, calling its `enhanceApp` before ours
* @optional
*/
extends?: Theme
}
interface EnhanceAppContext {
app: App // Vue app instance
router: Router // VitePress router instance
siteData: Ref<SiteData> // Site-level metadata
}
```
The theme entry file should export the theme as its default export:
```js
// .vitepress/theme/index.js
// You can directly import Vue files in the theme entry
// VitePress is pre-configured with @vitejs/plugin-vue.
import Layout from './Layout.vue'
export default {
Layout,
enhanceApp({ app, router, siteData }) {
// ...
}
}
```
The default export is the only contract for a custom theme, and only the `Layout` property is required. So technically, a VitePress theme can be as simple as a single Vue component.
Inside your layout component, it works just like a normal Vite + Vue 3 application. Do note the theme also needs to be [SSR-compatible](./using-vue#browser-api-access-restrictions).
## Building a Layout
The most basic layout component needs to contain a [`<Content />`](/reference/runtime-api#content) component:
```vue
<!-- .vitepress/theme/Layout.vue -->
<template>
<h1>Custom Layout!</h1>
<!-- this is where markdown content will be rendered -->
<Content />
</template>
```
The above layout simply renders every page's markdown as HTML. The first improvement we can add is to handle 404 errors:
```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>
```
The [`useData()`](/reference/runtime-api#usedata) helper provides us with all the runtime data we need to conditionally render different layouts. One of the other data we can access is the current page's frontmatter. We can leverage this to allow the end user to control the layout in each page. For example, the user can indicate the page should use a special home page layout with:
```md
---
layout: home
---
```
And we can adjust our theme to handle this:
```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>
```
You can, of course, split the layout into more components:
```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 /> renders <Content /> -->
</template>
```
Consult the [Runtime API Reference](/reference/runtime-api) for everything available in theme components. In addition, you can leverage [Build-Time Data Loading](./data-loading) to generate data-driven layout - for example, a page that lists all blog posts in the current project.
## Distributing a Custom Theme
The easiest way to distribute a custom theme is by providing it as a [template repository on GitHub](https://docs.github.com/en/repositories/creating-and-managing-repositories/creating-a-template-repository).
If you wish to distribute the theme as an npm package, follow these steps:
1. Export the theme object as the default export in your package entry.
2. If applicable, export your theme config type definition as `ThemeConfig`.
3. If your theme requires adjusting the VitePress config, export that config under a package sub-path (e.g. `my-theme/config`) so the user can extend it.
4. Document the theme config options (both via config file and frontmatter).
5. Provide clear instructions on how to consume your theme (see below).
## Consuming a Custom Theme
To consume an external theme, import and re-export it from the custom theme entry:
```js
// .vitepress/theme/index.js
import Theme from 'awesome-vitepress-theme'
export default Theme
```
If the theme needs to be extended:
```js
// .vitepress/theme/index.js
import Theme from 'awesome-vitepress-theme'
export default {
extends: Theme,
enhanceApp(ctx) {
// ...
}
}
```
If the theme requires special VitePress config, you will need to also extend it in your own config:
```ts
// .vitepress/theme/config.ts
import baseConfig from 'awesome-vitepress-theme/config'
export default {
// extend theme base config (if needed)
extends: baseConfig
}
```
Finally, if the theme provides types for its theme config:
```ts
// .vitepress/theme/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: {
// Type is `ThemeConfig`
}
})
```

@ -1,220 +0,0 @@
# 主题介绍 {#theme-introduction}
VitePress 带有默认主题,并提供许多开箱即用的功能。通过下面列出的导航来了解有关每个功能的更多信息。
- [导航](./theme-nav)
- [侧边栏](./theme-sidebar)
- [上一页/下一页链接](./theme-prev-next-link)
- [编辑链接](./theme-edit-link)
- [最后更新](./theme-last-updated)
- [布局](./theme-layout)
- [主页](./theme-home-page)
- [团队页面](./theme-team-page)
- [页脚](./theme-footer)
- [搜索](./theme-search)
- [Carbon Ads](./theme-carbon-ads)
如果你没有找到所需的功能,或者你想创建自己的主题,你可以自定义 VitePress 以满足你的要求。在下面,我们将介绍自定义 VitePress 主题的方式。
## 使用自定义主题 {#using-a-custom-theme}
你可以通过添加 `.vitepress/theme/index.js``.vitepress/theme/index.ts` 文件 (“主题入口文件”) 来启用自定义主题。
```
.
├─ docs
│ ├─ .vitepress
│ │ ├─ theme
│ │ │ └─ index.js
│ │ └─ config.js
│ └─ index.md
└─ package.json
```
VitePress 自定义主题是一个只包含四个属性的对象,定义如下:
```ts
interface Theme {
Layout: Component // Vue 3 component
NotFound?: Component
enhanceApp?: (ctx: EnhanceAppContext) => void
setup?: () => void
}
interface EnhanceAppContext {
app: App // Vue 3 app instance
router: Router // VitePress router instance
siteData: Ref<SiteData>
}
```
主题入口文件应将主题作为其默认导出:
```js
// .vitepress/theme/index.js
import Layout from './Layout.vue'
export default {
// root component to wrap each page
Layout,
// this is a Vue 3 functional component
NotFound: () => 'custom 404',
enhanceApp({ app, router, siteData }) {
// app is the Vue 3 app instance from `createApp()`.
// router is VitePress' custom router. `siteData` is
// a `ref` of current site-level metadata.
}
setup() {
// this function will be executed inside VitePressApp's
// setup hook. all composition APIs are available here.
}
}
```
... `Layout` 组件会如下所示:
```vue
<!-- .vitepress/theme/Layout.vue -->
<template>
<h1>Custom Layout!</h1>
<!-- this is where markdown content will be rendered -->
<Content />
</template>
```
默认导出是自定义主题的唯一方式。 在自定义主题中,它就像普通的 Vite + Vue 3 应用程序一样工作。 注意,主题还需要[兼容 SSR](./using-vue#browser-api-access-restrictions)。
要分发主题,只需在包入口里导出对象。要使用外部主题,请从自定义主题入口导入并重新导出:
```js
// .vitepress/theme/index.js
import Theme from 'awesome-vitepress-theme'
export default Theme
```
## 扩展默认主题 {#extending-the-default-theme}
如果你想扩展和自定义默认主题,你可以从 `vitepress/theme` 导入它并在导出自定义主题中对其进行扩展。以下是一些常见自定义的示例:
### 注册全局组件 {#registering-global-components}
```js
// .vitepress/theme/index.js
import DefaultTheme from 'vitepress/theme'
export default {
...DefaultTheme,
enhanceApp({ app }) {
// 注册一个全局组件
app.component('MyGlobalComponent', /* ... */)
}
}
```
由于我们使用 Vite你还可以利用 Vite 的[全局导入特性](https://vitejs.dev/guide/features.html#glob-import)自动注册组件目录。
### 自定义 CSS {#customizing-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: #646cff;
--vp-c-brand-light: #747bff;
}
```
请参阅可以被覆盖的[默认的主题 CSS 变量](https://github.com/vuejs/vitepress/blob/main/src/client/theme-default/styles/vars.css)。
### Layout 组件插槽 {#layout-slots}
默认主题 `<Layout/>` 组件有一些插槽,可用于在页面的某些位置注入内容。 这是一个将组件注入到之前的大纲中的示例:
```js
// .vitepress/theme/index.js
import DefaultTheme from 'vitepress/theme'
import MyLayout from './MyLayout.vue'
export default {
...DefaultTheme,
// override the Layout with a wrapper component that
// injects the slots
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 DefaultTheme from 'vitepress/theme'
import MyComponent from './MyComponent.vue'
export default {
...DefaultTheme,
Layout() {
return h(DefaultTheme.Layout, null, {
'aside-outline-before': () => h(MyComponent)
})
}
}
```
默认主题布局中可用插槽的完整列表:
- 当通过 frontmatter 开启 `layout: 'doc'` (default):
- `doc-footer-before`
- `doc-before`
- `doc-after`
- `aside-top`
- `aside-bottom`
- `aside-outline-before`
- `aside-outline-after`
- `aside-ads-before`
- `aside-ads-after`
- 当通过 frontmatter 开启 `layout: 'home'`:
- `home-hero-before`
- `home-hero-info`
- `home-hero-after`
- `home-features-before`
- `home-features-after`
- 一定有的:
- `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`

@ -1,6 +1,15 @@
# Build-Time Data Loading
VitePress provides a feature called **data loaders** that allows you to load arbitrary data and import it from pages or components. The data loading is executed **only at build time**: the resulting data will be serialized as JSON in the final JavaScript bundle.
Data loaders can be used to fetch remote data, or generate metadata based on local files. For example, you can use data loaders to parse all your local API pages and automatically generate an index of all API entries.
## Basic Usage
A data loader file must end with either `.data.js` or `.data.ts`. The file should provide a default export of an object with the `load()` method:
```js
// example.data.js
export default {
load() {
return {
@ -10,30 +19,76 @@ export default {
}
```
The loader module is evaluated only in Node.js, so you can import Node APIs and npm dependencies as needed.
You can then import data from this file in `.md` pages and `.vue` components using the `data` named export:
```html
<script setup>
import { data } from './example.data.js'
</script>
<pre>{{ data }}</pre>
```
Output:
```json
{
"data": "hello"
}
```
You'll notice the data loader itself does not export the `data`. It is VitePress calling the `load()` method behind the scenes and implicitly exposing the result via the `data` named export.
This works even if the loader is async:
```js
export default {
async load() {
// fetch remote data
return (await fetch('...')).json()
}
}
```
## Generating Data Based On Local Files
## Data from Local Files
When you need to generate data based on local files, you should use the `watch` option in the data loader so that changes made to these files can trigger hot updates.
The `watch` option is also convenient in that you can use [glob patterns](https://github.com/mrmlnc/fast-glob#pattern-syntax) to match multiple files. The patterns can be relative to the loader file itself, and the `load()` function will receive the matched files as absolute paths:
```js
import { readDirSync } from 'node:fs'
import fs from 'node:fs'
import parseFrontmatter from 'gray-matter'
export default {
watch: ['*.md'],
async load() {
//
// watch all blog posts
watch: ['./posts/*.md'],
load(watchedFiles) {
// watchedFiles will be an array of absolute paths of the matched files.
// generate an array of blog post metadata that can be used to render
// a list in the theme layout
return watchedFiles.map(file => {
const content = fs.readFileSync(file, 'utf-8')
const { data, excerpt } = parseFrontmatter(content)
return {
file,
data,
excerpt
}
})
}
}
```
## Typed Data
## Typed Data Loaders
When using TypeScript, you can type your loader and `data` export like so:
```ts
import { defineLoader } from 'vitepress'
export interface Data {
// data type
}
@ -41,9 +96,11 @@ export interface Data {
declare const data: Data
export { data }
export default {
export default defineLoader({
// type checked loader options
glob: ['...'],
async load(): Promise<Data> {
// ...
}
}
})
```

@ -0,0 +1,230 @@
# Deploy Your VitePress Site
The following guides are based on some shared assumptions:
- You are placing your docs inside the `docs` directory of your project.
- You are using the default build output location (`.vitepress/dist`).
- VitePress is installed as a local dependency in your project, and you have set up the following scripts in your `package.json`:
```json
{
"scripts": {
"docs:build": "vitepress build docs",
"docs:preview": "vitepress preview docs"
}
}
```
::: tip
If your site is to be served at a subdirectory (`https://example.com/subdir/`), then you have to set `'/subdir/'` as the [`base`](/reference/site-config#base) in your `docs/.vitepress/config.js`.
**Example:** If you're using Github (or GitLab) Pages and deploying to `user.github.io/repo/`, then set your `base` to `/repo/`.
:::
## Build and Test Locally
- You may run this command to build the docs:
```sh
$ npm run docs:build
```
- Once you've built the docs, you can test them locally by running:
```sh
$ npm run docs:preview
```
The `preview` command will boot up a local static web server that will serve the files from `.vitepress/dist` at `http://localhost:4173`. It's an easy way to check if the production build looks fine in your local environment.
- You can configure the port of the server by passing `--port` as an argument.
```json
{
"scripts": {
"docs:preview": "vitepress preview docs --port 8080"
}
}
```
Now the `docs:preview` method will launch the server at `http://localhost:8080`.
## Netlify, Vercel, AWS Amplify, Cloudflare Pages, Render
Set up a new project and change these settings using your dashboard:
- **Build Command:** `npm run docs:build`
- **Output Directory:** `docs/.vitepress/dist`
- **Node Version:** `14` (or above, by default it usually will be 14 or 16, but on Cloudflare Pages the default is still 12, so you may need to [change that](https://developers.cloudflare.com/pages/platform/build-configuration/))
::: warning
Don't enable options like _Auto Minify_ for HTML code. It will remove comments from output which have meaning to Vue. You may see hydration mismatch errors if they get removed.
:::
## GitHub Pages
### Using GitHub Actions
1. In your theme config file, `docs/.vitepress/config.js`, set the `base` property to the name of your GitHub repository. 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.
2. Create a file named `deploy.yml` inside `.github/workflows` directory of your project with the following content:
```yaml
name: Deploy
on:
workflow_dispatch: {}
push:
branches:
- main
jobs:
deploy:
runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- uses: actions/checkout@v3
with:
fetch-depth: 0
- uses: actions/setup-node@v3
with:
node-version: 16
cache: npm
- run: npm install --frozen-lockfile
- name: Build
run: npm run docs:build
- uses: actions/configure-pages@v2
- uses: actions/upload-pages-artifact@v1
with:
path: docs/.vitepress/dist
- name: Deploy
id: deployment
uses: actions/deploy-pages@v1
```
::: tip
Please replace the corresponding branch name. For example, if the branch you want to build is `master`, then you should replace `main` with `master` in the above file.
:::
3. In your repository's Settings under Pages menu item, select `GitHub Actions` in Build and deployment's Source.
4. Now commit your code and push it to the `main` branch.
5. Wait for actions to complete.
6. In your repository's Settings under Pages menu item, click `Visit site`, then you can see your site. Your docs will automatically deploy each time you push.
## GitLab Pages
### Using GitLab CI
1. Set `outDir` in `docs/.vitepress/config.js` to `../public`.
2. Still in your config file, `docs/.vitepress/config.js`, set the `base` property to the name of your GitLab repository. If you plan to deploy your site to `https://foo.gitlab.io/bar/`, then you should set base to `'/bar/'`. It should always start and end with a slash.
3. Create a file called `.gitlab-ci.yml` in the root of your project with the content below. This will build and deploy your site whenever you make changes to your content:
```yaml
image: node:16
pages:
cache:
paths:
- node_modules/
script:
- npm install
- npm run docs:build
artifacts:
paths:
- public
only:
- main
```
4. Alternatively, if you want to use an _alpine_ version of node, you have to install `git` manually. In that case, the code above modifies to this:
```yaml
image: node:16-alpine
pages:
cache:
paths:
- node_modules/
before_script:
- apk add git
script:
- npm install
- npm run docs:build
artifacts:
paths:
- public
only:
- main
```
## Azure Static Web Apps
1. Follow the [official documentation](https://docs.microsoft.com/en-us/azure/static-web-apps/build-configuration).
2. Set these values in your configuration file (and remove the ones you don't require, like `api_location`):
- **`app_location`**: `/`
- **`output_location`**: `docs/.vitepress/dist`
- **`app_build_command`**: `npm run docs:build`
## Firebase
1. Create `firebase.json` and `.firebaserc` at the root of your project:
`firebase.json`:
```json
{
"hosting": {
"public": "docs/.vitepress/dist",
"ignore": []
}
}
```
`.firebaserc`:
```json
{
"projects": {
"default": "<YOUR_FIREBASE_ID>"
}
}
```
2. After running `npm run docs:build`, run this command to deploy:
```sh
firebase deploy
```
## Surge
1. After running `npm run docs:build`, run this command to deploy:
```sh
npx surge docs/.vitepress/dist
```
## Heroku
1. Follow documentation and guide given in [`heroku-buildpack-static`](https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-static).
2. Create a file called `static.json` in the root of your project with the below content:
```json
{
"root": "docs/.vitepress/dist"
}
```
## Edgio
Refer [Creating and Deploying a VitePress App To Edgio](https://docs.edg.io/guides/vitepress).

@ -1,225 +0,0 @@
# 部署 {#deploying}
指南基于以下前置环境:
- 文档放在项目的 `docs` 目录中。
- 使用默认的构建输出位置 (`.vitepress/dist`)。
- VitePress 作为本地依赖安装在项目中,并且在 `package.json` 中设置了以下脚本:
```json
{
"scripts": {
"docs:build": "vitepress build docs",
"docs:serve": "vitepress serve docs"
}
}
```
::: tip 提示
如果使用子目录(`https://example.com/subdir/`)作为部署站点,则必须在 `docs/.vitepress/config.js` 中将 `'/subdir/'` 设置为 [`base`](../config/app-config#base) 的值。
**示例:** 如果你使用 Github (或 GitLab) 页面并部署到 `user.github.io/repo/`,则将 `base` 设置为 `/repo/`
:::
## 本地打包和测试 {#build-and-test-locally}
- 运行此命令来打包文档:
```sh
$ npm run docs:build
```
- 打包文档后,你可以通过运行命令在本地进行调试:
```sh
$ npm run docs:serve
```
`serve` 命令将启动一个本地静态 Web 服务,该服务将在 `http://localhost:4173` 输出来自 `.vitepress/dist` 的文件。 这是检查生产版本在你的本地环境中是否正常的简易方法。
- 可以通过传递 `--port` 作为参数来配置服务器运行的端口。
```json
{
"scripts": {
"docs:serve": "vitepress serve docs --port 8080"
}
}
```
现在 `docs:serve` 方法将在 `http://localhost:8080` 启动服务器。
## 在 Netlify, Vercel, AWS Amplify, Cloudflare Pages 里部署 {#netlify-vercel-aws-amplify-cloudflare-pages-render}
创建一个新项目并改成以下这些设置:
- **Build Command:** `npm run docs:build`
- **Output Directory:** `docs/.vitepress/dist`
- **Node Version:** `14` (或者更高,默认值通常是 14 或 16但在 Cloudflare Pages 上,默认值仍然是 12所以你可能需要[修改](https://developers.cloudflare.com/pages/platform/build-configuration/))。
::: warning 警告
不要为 HTML 代码启用 _Auto Minify_ 之类的选项。 它将从输出中删除对 Vue 有意义的注释。如果它们被删除,可能会出现页面 hydration 不正确的问题。
:::
## GitHub Pages
### 使用 GitHub Actions {#using-github-actions}
1. 在你的主题配置文件 `docs/.vitepress/config.js` 中,将 `base` 属性设置为你的 GitHub 仓库的名称。 如果你打算将你的站点部署到 `https://foo.github.io/bar/`,那么你应该将 base 设置为`'/bar/'`。 它应该始终以斜线开头和结尾。
2. 在项目的 `.github/workflows` 目录中创建一个名为 `deploy.yml` 的文件,内容如下:
```yaml
name: Deploy
on:
workflow_dispatch: {}
push:
branches:
- main
jobs:
deploy:
runs-on: ubuntu-latest
permissions:
pages: write
id-token: write
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
steps:
- uses: actions/checkout@v3
with:
node-version: 16
cache: npm
- run: npm install --frozen-lockfile
- name: Build
run: npm run docs:build
- uses: actions/configure-pages@v2
- uses: actions/upload-pages-artifact@v1
with:
path: docs/.vitepress/dist
- name: Deploy
id: deployment
uses: actions/deploy-pages@v1
```
::: tip 提示
请替换对应的分支名称。例如,如果你要构建的分支是 `master`,则应将上述文件中的 `main` 替换为 `master`
:::
3. In your repository's Settings under Pages menu item, select `GitHub Actions` in Build and deployment's Source.
4. 现在提交你的代码并将其推送到 `main` 分支。
5. 等待 action 完成。
6. 在 git 仓库的 Setting 选项里,选择 `gh-pages` 分支作为 GitHub Pages 的来源。现在,你的文档将在每次推送时自动部署。
## GitLab Pages
### 使用 GitLab CI {#using-gitlab-ci}
1. 将 `docs/.vitepress/config.js` 中的 `outDir` 设置为 `../public`
2. 在项目的根目录中创建一个名为 `.gitlab-ci.yml` 的文件,内容如下。每更改内容时,将会构建和部署你的站点:
```yaml
image: node:16
pages:
cache:
paths:
- node_modules/
script:
- npm install
- npm run docs:build
artifacts:
paths:
- public
only:
- main
```
4. Alternatively, if you want to use an _alpine_ version of node, you have to install `git` manually. In that case, the code above modifies to this:
```yaml
image: node:16-alpine
pages:
cache:
paths:
- node_modules/
before_script:
- apk add git
script:
- 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
{
"hosting": {
"public": "docs/.vitepress/dist",
"ignore": []
}
}
```
`.firebaserc`:
```json
{
"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
{
"root": "docs/.vitepress/dist"
}
```
## Edgio
参考[在 Edgio 里创建和部署 VitePress 应用](https://docs.edg.io/guides/vitepress)。

@ -0,0 +1,138 @@
# Extending the Default Theme
VitePress' default theme is optimized for documentation, and can be customized. Consult the [Default Theme Config Overview](/reference/default-theme-config) for a comprehensive list of options.
However, there are a number of cases where configuration alone won't be enough. For example:
1. You need to tweak the CSS styling;
2. You need to modify the Vue app instance, for example to register global components;
3. You need to inject custom content into the theme via layout slots.
These advanced customizations will require using a custom theme that "extends" the default theme.
:::tip
Before proceeding, make sure to first read [Using a Custom Theme](./custom-theme) to understand how custom themes work.
:::
## Customizing CSS
The default theme CSS is customizable by overriding root level CSS variables:
```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: #646cff;
--vp-c-brand-light: #747bff;
}
```
See [default theme CSS variables](https://github.com/vuejs/vitepress/blob/main/src/client/theme-default/styles/vars.css) that can be overridden.
## Registering Global Components
```js
// .vitepress/theme/index.js
import DefaultTheme from 'vitepress/theme'
export default {
extends: DefaultTheme,
enhanceApp(ctx) {
// register your custom global components
ctx.app.component('MyGlobalComponent' /* ... */)
}
}
```
Since we are using Vite, you can also leverage Vite's [glob import feature](https://vitejs.dev/guide/features.html#glob-import) to auto register a directory of components.
## Layout Slots
The default theme's `<Layout/>` component has a few slots that can be used to inject content at certain locations of the page. Here's an example of injecting a component into the before outline:
```js
// .vitepress/theme/index.js
import DefaultTheme from 'vitepress/theme'
import MyLayout from './MyLayout.vue'
export default {
...DefaultTheme,
// override the Layout with a wrapper component that
// injects the slots
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>
```
Or you could use render function as well.
```js
// .vitepress/theme/index.js
import { h } from 'vue'
import DefaultTheme from 'vitepress/theme'
import MyComponent from './MyComponent.vue'
export default {
...DefaultTheme,
Layout() {
return h(DefaultTheme.Layout, null, {
'aside-outline-before': () => h(MyComponent)
})
}
}
```
Full list of slots available in the default theme layout:
- When `layout: 'doc'` (default) is enabled via frontmatter:
- `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`
- When `layout: 'home'` is enabled via frontmatter:
- `home-hero-before`
- `home-hero-info`
- `home-hero-image`
- `home-hero-after`
- `home-features-before`
- `home-features-after`
- Always:
- `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`

@ -1,6 +1,8 @@
# Frontmatter
任何包含 YAML frontmatter 的 Markdown 文件都将由 [gray-matter](https://github.com/jonschlinkert/gray-matter) 处理。 frontmatter 必须位于 Markdown 文件的顶部,并且必须采用在三点划线之间设置的有效 YAML 的形式。例如:
## Usage
VitePress supports YAML frontmatter in all Markdown files, parsing them with [gray-matter](https://github.com/jonschlinkert/gray-matter). The frontmatter must be at the top of the Markdown file (before any elements including `<script>` tags), and must take the form of valid YAML set between triple-dashed lines. Example:
```md
---
@ -9,9 +11,15 @@ editLink: true
---
```
在三点虚线之间,你可以设置[预定义变量](../config/frontmatter-config),甚至可以创建自己的自定义变量。 这些变量可以通过特殊的 <code>$frontmatter</code> 变量来使用。
Many site or default theme config options have corresponding options in frontmatter. You can use frontmatter to override specific behavior for the current page only. For details, see [Frontmatter Config Reference](/reference/frontmatter-config).
You can also define custom frontmatter data of your own, to be used in dynamic Vue expressions on the page.
## Accessing Frontmatter Data
这是如何在 Markdown 文件中使用的例子:
Frontmatter data can be accessed via the special `$frontmatter` global variable:
Here's an example of how you could use it in your Markdown file:
```md
---
@ -24,9 +32,11 @@ editLink: true
Guide content
```
## Frontmatter 格式的其他写法 {#alternative-frontmatter-formats}
You can also access current page's frontmatter data in `<script setup>` with the [`useData()`](/reference/runtime-api#usedata) helper.
## Alternative Frontmatter Formats
VitePress 还支持 JSON frontmatter 语法,以花括号开头和结尾:
VitePress also supports JSON frontmatter syntax, starting and ending in curly braces:
```json
---

@ -1,86 +1,130 @@
# 快速上手 {#getting-started}
# Getting Started
本节将帮助你从头开始构建一个基本的 VitePress 文档站点。如果你已经有一个现有项目并希望将文档保留在项目中请从步骤2开始。
## Try It Online
你也可以在 [StackBlitz](https://vitepress.new/) 上在线尝试 VitePress它直接在浏览器里运行基于 Vite 的站点。所以和你在本地构建的效果几乎是一样的,但是这种方式不需要在你的机器上安装任何东西。
You can try VitePress directly in your browser on [StackBlitz](https://vitepress.new).
::: warning
VitePress 目前处于 `alpha` 状态。它已经适合开箱即用地组织文档,但是具体配置以及和主题相关的 API 仍然可能在小的版本之间发生变化。
:::
## 步骤 1创建一个项目 {#step-1-create-a-new-project}
## Installation
创建并进入新项目的目录。
### Prerequisites
- [Node.js](https://nodejs.org/) version 16 or higher.
- Terminal for accessing VitePress via its command line interface (CLI).
- Text Editor with [Markdown](https://en.wikipedia.org/wiki/Markdown) syntax support.
- [VSCode](https://code.visualstudio.com/) is recommended, along with the [official Vue extension](https://marketplace.visualstudio.com/items?itemName=Vue.volar).
```sh
$ mkdir vitepress-starter && cd vitepress-starter
```
用你喜欢的包管理工具初始化项目。
VitePress can be used on its own, or be installed into an existing project. In both cases, you can install it with:
::: code-group
```sh [npm]
$ npm init
$ npm install -D vitepress
```
```sh [pnpm]
$ pnpm add -D vitepress
```
```sh [yarn]
$ yarn init
$ yarn add -D vitepress
```
```sh [pnpm]
$ pnpm init
:::
::: details Getting missing peer deps warnings?
If using PNPM, you will notice a missing peer warning for `@docsearch/js`. This does not prevent VitePress from working. If you wish to suppress this warning, add the following to your `package.json`:
```json
"pnpm": {
"peerDependencyRules": {
"ignoreMissing": [
"@algolia/client-search"
]
}
}
```
:::
## 步骤 2安装 VitePress {#step-2-install-vitepress}
### Setup Wizard
添加 VitePress 和 Vue 作为项目的开发依赖项。
VitePress ships with a command line setup wizard that will help you scaffold a basic project. After installation, start the wizard by running:
::: code-group
```sh [npm]
$ npm install -D vitepress vue
$ npx vitepress init
```
```sh [yarn]
$ yarn add -D vitepress vue
```sh [pnpm]
$ pnpm exec vitepress init
```
```sh [pnpm]
$ pnpm add -D vitepress vue
:::
You will be greeted with a few simple questions:
<p>
<img src="./vitepress-init.png" alt="vitepress init screenshot" style="border-radius:8px">
</p>
:::tip Vue as Peer Dependency
If you intend to perform customization that uses Vue components or APIs, you should also explicitly install `vue` as a peer dependency.
:::
## File Structure
If you are building a standalone VitePress site, you can scaffold the site in your current directory (`./`). However, if you are installing VitePress in an existing project alongside other source code, it is recommended to scaffold the site in a nested directory (e.g. `./docs`) so that it is separate from the rest of the project.
Assuming you chose to scaffold the VitePress project in `./docs`, the generated file structure should look like this:
```
.
├─ docs
│ ├─ .vitepress
│ │ └─ config.js
│ ├─ api-examples.md
│ ├─ markdown-examples.md
│ └─ index.md
└─ package.json
```
The `docs` directory is considered the **project root** of the VitePress site. The `.vitepress` directory is a reserved location for VitePress' config file, dev server cache, build output, and optional theme customization code.
:::tip
By default, VitePress stores its dev server cache in `.vitepress/cache`, and the production build output in `.vitepress/dist`. If using Git, you should add them to your `.gitignore` file. These locations can also be [configured](/reference/site-config#outdir).
:::
::: details 得到了 peer dependencies 警告?
`@docsearch/js` 的 peer dependencies 存在某些问题。如果你看到某些命令由于它们而失败,你现在可以尝试以下解决方案:
### The Config File
如果使用 pnpm`package.json` 添加以下代码:
The config file (`.vitepress/config.js`) allows you to customize various aspects of your VitePress site, with the most basic options being the title and description of the site:
```json
"pnpm": {
"peerDependencyRules": {
"ignoreMissing": [
"@algolia/client-search"
]
```js
// .vitepress/config.js
export default {
// site-level options
title: 'VitePress',
description: 'Just playing around.',
themeConfig: {
// theme-level options
}
}
```
:::
You can also configure the behavior of the theme via the `themeConfig` option. Consult the [Config Reference](/reference/site-config) for full details on all config options.
创建你的第一篇文档。
### Source Files
```sh
$ mkdir docs && echo '# Hello VitePress' > docs/index.md
```
Markdown files outside the `.vitepress` directory are considered **source files**.
VitePress uses **file-based routing**: each `.md` file is compiled into a corresponding `.html` file with the same path. For example, `index.md` will be compiled into `index.html`, and can be visited at the root path `/` of the resulting VitePress site.
## 步骤 3启动本地开发环境 {#step-3-boot-up-dev-environment}
VitePress also provides the ability to generate clean URLs, rewrite paths, and dynamically generate pages. These will be covered in the [Routing Guide](./routing).
`package.json` 里添加一些脚本。
## Up and Running
The tool should have also injected the following npm scripts to your `package.json` if you allowed it to do so during the setup process:
```json
{
@ -88,13 +132,13 @@ $ mkdir docs && echo '# Hello VitePress' > docs/index.md
"scripts": {
"docs:dev": "vitepress dev docs",
"docs:build": "vitepress build docs",
"docs:serve": "vitepress serve docs"
"docs:preview": "vitepress preview docs"
},
...
}
```
在本地启动文档服务。
The `docs:dev` script will start a local dev server with instant hot updates. Run it with the following command:
::: code-group
@ -102,42 +146,42 @@ $ mkdir docs && echo '# Hello VitePress' > docs/index.md
$ npm run docs:dev
```
```sh [yarn]
$ yarn docs:dev
```
```sh [pnpm]
$ pnpm run docs:dev
```
:::
```sh [yarn]
$ yarn docs:dev
```
VitePress 将在 `http://localhost:5173` 启动一个支持热部署的本地开发服务环境。
:::
## 步骤 4添加更多文档 {#step-4-add-more-pages}
Instead of npm scripts, you can also invoke VitePress directly with:
让我们再添加一个页面,创建一个名为 `getting-started.md` 的文件,与前面创建的 `index.md` 放在同一目录下。现在你的目录结构应该是这样的。
::: code-group
```sh [npm]
$ npx vitepress dev docs
```
.
├─ docs
│ ├─ getting-started.md
│ └─ index.md
└─ package.json
```sh [pnpm]
$ pnpm exec vitepress dev docs
```
接下来,访问 `http://localhost:5173/getting-started.html`,可以看到 `getting-started.md` 的内容。
:::
More command line usage is documented in the [CLI Reference](/reference/cli).
这就是 VitePress 的基本工作方式。目录结构与 URL 路径相对应。你可以添加文件,然后尝试访问它。
The dev server should be running at `http://localhost:5173`. Visit the URL in your browser to see your new site in action!
## 下一步? {#what-s-next}
## What's Next?
到目前为止,你应该拥有一个基本但功能强大的 VitePress 文档站点。但现在用户还无法浏览该站点,因为它缺少菜单,类似于这个站点上的侧边栏。
- To better understand how markdown files are mapped to generated HTML, proceed to the [Routing Guide](./routing.md).
要启用这些导航,我们必须向站点添加一些配置。前往[配置指南](./configuration)了解如何配置 VitePress。
- To discover more about what you can do on the page, such as writing markdown content or using Vue Component, refer to the "Writing" section of the guide. A great place to start would be to learn about [Markdown Extensions](/guide/markdown).
如果你想了解更多关于可以在页面中执行的操作,例如编写 Markdown 或使用 Vue 组件,请查看文档的“编写”部分。[Markdown 指南](./markdown)将是一个很好的起点。
- To explore the features provided by the default documentation theme, check out the [Default Theme Config Reference](/reference/default-theme-config).
如果你想了解如何自定义站点外观(主题),并了解 VitePress 默认主题提供的功能,请访问[主题:简介](./customization-intro)。
- If you want to further customize the appearance of your site, explore how to either [Extend the Default Theme](./extending-default-theme) or [Build a Custom Theme](./custom-theme).
当你的文档站点已经成形准备部署时,请务必阅读[部署指南](./deploying)。
- Once your documentation site takes shape, make sure to read the [Deployment Guide](./deploy).

@ -1,6 +1,6 @@
# 国际化 {#internationalization}
# Internationalization
你可以创建如下的目录结构来使你的站点国际化:
To use the built-in i18n features, one needs to create a directory structure as follows:
```
docs/
@ -11,7 +11,7 @@ docs/
├─ foo.md
```
然后我们需要在 `docs/.vitepress/config.ts` 中作如下配置:
Then in `docs/.vitepress/config.ts`:
```ts
import { defineConfig } from 'vitepress'
@ -35,7 +35,7 @@ export default defineConfig({
})
```
每个语言环境 (包括根目录) 都可以覆盖以下属性:
The following properties can be overridden for each locale (including root):
```ts
interface LocaleSpecificConfig<ThemeConfig = any> {
@ -49,13 +49,13 @@ interface LocaleSpecificConfig<ThemeConfig = any> {
}
```
参见 [`DefaultTheme.Config`](https://github.com/vuejs/vitepress/blob/main/types/default-theme.d.ts) 接口,可以获得有关自定义的默认主题的占位符文本的详细信息。不要在本地环境这个层级上覆盖 `themeConfig.algolia` 或者 `themeConfig.carbonAds`。可以参见 [Algolia 的文档](./theme-search#i18n) 以定制多种语言的搜索。
Refer [`DefaultTheme.Config`](https://github.com/vuejs/vitepress/blob/main/types/default-theme.d.ts) interface for details on customizing the placeholder texts of the default theme. Don't override `themeConfig.algolia` or `themeConfig.carbonAds` at locale-level. Refer [Algolia docs](/reference/default-theme-search#i18n) for using multilingual search.
**重要提示:** 也可以在 `docs/.vitepress/config/index.ts` 进行配置。它可以为每个语言环境创建一个配置文件,帮助你组织这些东西,然后你可以从 `index.ts` 合并并导出它们。
**Pro tip:** Config file can be stored at `docs/.vitepress/config/index.ts` too. It might help you organize stuff by creating a configuration file per locale and then merge and export them from `index.ts`.
## 语言环境独有的目录结构 {#separate-directory-for-each-locale}
## Separate directory for each locale
下面这样的目录当然很不错:
The following is a perfectly fine structure:
```
docs/
@ -67,7 +67,7 @@ docs/
├─ foo.md
```
但是 VitePress 不会将 `/` 重定向至 `/en/`。你需要在服务器上自行配置。例如,在 Netlify 上,你可以添加一个像这样的 `docs/public/_redirects` 文件:
However, VitePress won't redirect `/` to `/en/` by default. You'll need to configure your server for that. For example, on Netlify, you can add a `docs/public/_redirects` file like this:
```
/* /es/:splat 302 Language=es
@ -75,7 +75,7 @@ docs/
/* /en/:splat 302
```
**重要提示:** 如果使用上面的方法,你可以使用 `nf_lang` cookie 去存储用户的语言偏好。如下是一个非常基本的例子,在自定义主题的 [setup](./customization-intro#using-a-custom-theme) 函数里面,你可以这样做:
**Pro tip:** If using the above approach, you can use `nf_lang` cookie to persist user's language choice. A very basic way to do this is register a watcher inside the [setup](./custom-theme#using-a-custom-theme) function of custom theme:
```ts
// docs/.vitepress/theme/index.ts
@ -94,6 +94,6 @@ export default {
}
```
## RTL 支持 (处于实验阶段) {#rtl-support-experimental}
## RTL Support (Experimental)
要获得 RTL 支持,可以在配置文件中添加 `dir: 'rtl'` 并运用一些 RTLCSS PostCSS 插件,像 <https://github.com/MohammadYounes/rtlcss><https://github.com/vkalinichev/postcss-rtl> <https://github.com/elchininet/postcss-rtlcss>。你需要在你的 PostCSS 插件中进行一些配置,使用 `:where([dir="ltr"])``:where([dir="rtl"])` 作为前缀解决 CSS 特有的问题。
For RTL support, specify `dir: 'rtl'` in config and use some RTLCSS PostCSS plugin like <https://github.com/MohammadYounes/rtlcss>, <https://github.com/vkalinichev/postcss-rtl> or <https://github.com/elchininet/postcss-rtlcss>. You'll need to configure your PostCSS plugin to use `:where([dir="ltr"])` and `:where([dir="rtl"])` as prefixes to prevent CSS specificity issues.

@ -1,20 +1,20 @@
# Markdown 扩展 {#markdown-extensions}
# Markdown Extensions
VitePress 带有内置的 Markdown 扩展。
VitePress comes with built in Markdown Extensions.
## 标题锚点 {#header-anchors}
## Header Anchors
标题会自动获取锚点链接。可以通过 `markdown.anchor` 选项配置锚点的渲染。
Headers automatically get anchor links applied. Rendering of anchors can be configured using the `markdown.anchor` option.
## 链接 {#links}
## Links
内部链接和外部链接都会特殊处理。
Both internal and external links gets special treatments.
### 内部链接 {#internal-links}
### Internal Links
内部链接转换为 SPA 导航的路由链接。此外,每个子目录中包含的每个 `index.md` 都会自动转换为 `index.html`并带有相应的URL `/`
Internal links are converted to router link for SPA navigation. Also, every `index.md` contained in each sub-directory will automatically be converted to `index.html`, with corresponding URL `/`.
举个例子,现在有以下目录结构:
For example, given the following directory structure:
```
.
@ -29,31 +29,31 @@ VitePress 带有内置的 Markdown 扩展。
└─ four.md
```
`foo/one.md`:
And providing you are in `foo/one.md`:
```md
[Home](/) <!-- 点击跳转到根目录的 index.md -->
[foo](/foo/) <!-- 点击跳转到 foo 目录的 index.html -->
[foo heading](./#heading) <!-- 锚点会定位到 foo 的 heading 标题处 -->
[bar - three](../bar/three) <!-- 你可以不写后缀名 -->
[bar - three](../bar/three.md) <!-- 也可以加 .md -->
[bar - four](../bar/four.html) <!-- 或者加 .html -->
[Home](/) <!-- sends the user to the root index.md -->
[foo](/foo/) <!-- sends the user to index.html of directory foo -->
[foo heading](./#heading) <!-- anchors user to a heading in the foo index file -->
[bar - three](../bar/three) <!-- you can omit extension -->
[bar - three](../bar/three.md) <!-- you can append .md -->
[bar - four](../bar/four.html) <!-- or you can append .html -->
```
### 页面后缀 {#page-suffix}
### Page Suffix
默认情况下,页面和内部链接会生成带有 `.html` 的后缀。
Pages and internal links get generated with the `.html` suffix by default.
### 外部链接 {#external-links}
### External Links
外部的链接会自动识别并生成 `target="_blank" rel="noreferrer"` 的链接,如下:
Outbound links automatically get `target="_blank" rel="noreferrer"`:
- [vuejs.org](https://vuejs.org)
- [VitePress github 地址](https://github.com/vuejs/vitepress)
- [VitePress on GitHub](https://github.com/vuejs/vitepress)
## Frontmatter
[YAML frontmatter](https://jekyllrb.com/docs/front-matter/) 支持开箱即用:
[YAML frontmatter](https://jekyllrb.com/docs/front-matter/) is supported out of the box:
```yaml
---
@ -62,23 +62,23 @@ lang: en-US
---
```
该数据可用于页面的其他部分,以及所有自定义和主题化组件中。
This data will be available to the rest of the page, along with all custom and theming components.
了解更多,可以查看 [Frontmatter](./frontmatter)。
For more details, see [Frontmatter](/reference/frontmatter-config).
## GitHub 风格的表格 {#github-style-tables}
## GitHub-Style Tables
**输入**
**Input**
```
| Tables | Are | Cool |
| ------------- |:-------------:| -----:|
| Tables | Are | Cool |
| ------------- | :-----------: | ----: |
| col 3 is | right-aligned | $1600 |
| col 2 is | centered | $12 |
| zebra stripes | are neat | $1 |
| col 2 is | centered | $12 |
| zebra stripes | are neat | $1 |
```
**输出**
**Output**
| Tables | Are | Cool |
| ------------- | :-----------: | -----: |
@ -86,41 +86,41 @@ lang: en-US
| col 2 is | centered | \$12 |
| zebra stripes | are neat | \$1 |
## Emoji :tada: {#emoji}
## Emoji :tada:
**输入**
**Input**
```
:tada: :100:
```
**输出**
**Output**
:tada: :100:
可用的 emoji 可以通过[这里](https://github.com/markdown-it/markdown-it-emoji/blob/master/lib/data/full.json)了解。
A [list of all emojis](https://github.com/markdown-it/markdown-it-emoji/blob/master/lib/data/full.json) is available.
## 表格内容 {#table-of-contents}
## Table of Contents
**输入**
**Input**
```
[[toc]]
```
**输出**
**Output**
[[toc]]
可以使用 `markdown.toc` 选项配置 TOC 的渲染。
Rendering of the TOC can be configured using the `markdown.toc` option.
## 自定义容器 {#custom-containers}
## Custom Containers
自定义容器可以通过其类型、标题和内容来定义。
Custom containers can be defined by their types, titles, and contents.
### 默认标题
### Default Title
**输入**
**Input**
```md
::: info
@ -144,7 +144,7 @@ This is a details block.
:::
```
**输出**
**Output**
::: info
This is an info box.
@ -155,7 +155,7 @@ This is a tip.
:::
::: warning
This is a dangerous warning.
This is a warning.
:::
::: danger
@ -166,11 +166,11 @@ This is a dangerous warning.
This is a details block.
:::
### 自定义标题 {#custom-title}
### Custom Title
你可以通过在容器的“类型”后面添加文本来设置自定义标题。
You may set custom title by appending the text right after the "type" of the container.
**输入**
**Input**
````md
::: danger STOP
@ -184,7 +184,7 @@ console.log('Hello, VitePress!')
:::
````
**输出**
**Output**
::: danger STOP
Danger zone, do not proceed
@ -196,11 +196,11 @@ console.log('Hello, VitePress!')
```
:::
### `raw` {#raw}
### `raw`
这是一个特殊的容器,可以用来防止样式和路由与 VitePress 冲突。当你记录组件库的文档时,这尤其有用。你可能还想查看一下 [whyframe](https://whyframe.dev/docs/integrations/vitepress),以获得更好的隔离效果。
This is a special container that can be used to prevent style and router conflicts with VitePress. This is especially useful when you're documenting component libraries. You might also wanna check out [whyframe](https://whyframe.dev/docs/integrations/vitepress) for better isolation.
**语法**
**Syntax**
```md
::: raw
@ -208,9 +208,9 @@ Wraps in a <div class="vp-raw">
:::
```
`vp-raw` 类也可以直接用于元素,样式隔离目前是可选择的。
`vp-raw` class can be directly used on elements too. Style isolation is currently opt-in:
::: details 具体细节
::: details
- Install required deps with your preferred package manager:
@ -237,11 +237,11 @@ Wraps in a <div class="vp-raw">
:::
## 在代码块中高亮语法 {#syntax-highlighting-in-code-blocks}
## Syntax Highlighting in Code Blocks
VitePress 使用 [Shiki](https://shiki.matsu.io/) 的彩色文本来突出 Markdown 代码块中的语言语法。Shiki 支持多种编程语言,需要做的就是将有效的语言别名附加到代码块的开头反引号后:
VitePress uses [Shiki](https://shiki.matsu.io/) to highlight language syntax in Markdown code blocks, using coloured text. Shiki supports a wide variety of programming languages. All you need to do is append a valid language alias to the beginning backticks for the code block:
**输入**
**Input**
````
```js
@ -262,7 +262,7 @@ export default {
```
````
**输出**
**Output**
```js
export default {
@ -279,13 +279,13 @@ export default {
</ul>
```
在 Shiki 的仓库里有对应支持的[语言列表](https://github.com/shikijs/shiki/blob/main/docs/languages.md)。
A [list of valid languages](https://github.com/shikijs/shiki/blob/main/docs/languages.md) is available on Shiki's repository.
你还可以在应用全局配置中自定义语法高亮主题。有关详细信息,请参阅 [`markdown` 选项](../config/app-config#markdown)。
You may also customize syntax highlight theme in app config. Please see [`markdown` options](/reference/site-config#markdown) for more details.
## 代码块中定义行高亮 {#line-highlighting-in-code-blocks}
## Line Highlighting in Code Blocks
**输入**
**Input**
````
```js{4}
@ -299,7 +299,7 @@ export default {
```
````
**输出**
**Output**
```js{4}
export default {
@ -311,13 +311,13 @@ export default {
}
```
除了单行之外,还可以指定多个单行、连续几行或者一起定义:
In addition to a single line, you can also specify multiple single lines, ranges, or both:
- 连续几行: 例如 `{5-8}`、`{3-10}`、`{10-17}`
- 多个单行: 例如 `{4,7,9}`
- 连续几行和多个单行: 例如 `{4,7-13,16,23-27,40}`
- Line ranges: for example `{5-8}`, `{3-10}`, `{10-17}`
- Multiple single lines: for example `{4,7,9}`
- Line ranges and single lines: for example `{4,7-13,16,23-27,40}`
**输入**
**Input**
````
```js{1,4,6-8}
@ -335,7 +335,7 @@ export default { // Highlighted
```
````
**输出**
**Output**
```js{1,4,6-8}
export default { // Highlighted
@ -351,9 +351,9 @@ export default { // Highlighted
}
```
另外,也可以通过使用 `// [!code hl]` 注释直接实现行高亮。
Alternatively, it's possible to highlight directly in the line by using the `// [!code hl]` comment.
**输入**
**Input**
````
```js
@ -367,11 +367,11 @@ export default {
```
````
**输出**
**Output**
```js
export default {
data () {
data() {
return {
msg: 'Highlighted!' // [!code hl]
}
@ -379,13 +379,15 @@ export default {
}
```
## 在代码块中聚焦 {#focus-in-code-blocks}
## Focus in Code Blocks
Adding the `// [!code focus]` comment on a line will focus it and blur the other parts of the code.
在一行上添加 `// [!code focus]` 注释将聚焦这一行并模糊代码的其他部分。
Additionally, you can define a number of lines to focus using `// [!code focus:<lines>]`.
此外,可以使用 `// [!code focus:<lines>]` 定义聚焦的行数。
**Input**
**输入**
Note that only one space is required after `!code`, here are two to prevent processing.
````
```js
@ -399,11 +401,11 @@ export default {
```
````
**输出**
**Output**
```js
export default {
data () {
data() {
return {
msg: 'Focused!' // [!code focus]
}
@ -411,11 +413,13 @@ export default {
}
```
## 代码块中的颜色差异 {#colored-diffs-in-code-blocks}
## Colored Diffs in Code Blocks
Adding the `// [!code --]` or `// [!code ++]` comments on a line will create a diff of that line, while keeping the colors of the codeblock.
在一行上添加 `// [!code --]` 或者 `// [!code ++]` 注释将实现该行差异的展示,同时保持代码块的颜色。
**Input**
**输入**
Note that only one space is required after `!code`, here are two to prevent processing.
````
```js
@ -430,7 +434,7 @@ export default {
```
````
**输出**
**Output**
```js
export default {
@ -443,11 +447,13 @@ export default {
}
```
## 错误和警告
## Errors and Warnings in Code Blocks
Adding the `// [!code warning]` or `// [!code error]` comments on a line will color it accordingly.
在一行上添加 `// [!code warning]` 或者 `// [!code error]` 注释将使它变成相应的颜色。
**Input**
**输入**
Note that only one space is required after `!code`, here are two to prevent processing.
````
```js
@ -462,11 +468,11 @@ export default {
```
````
**输出**
**Output**
```js
export default {
data () {
data() {
return {
msg: 'Error', // [!code error]
msg: 'Warning' // [!code warning]
@ -475,9 +481,9 @@ export default {
}
```
## 行号 {#line-numbers}
## Line Numbers
可以通过配置为每个代码块启用行号:
You can enable line numbers for each code blocks via config:
```js
export default {
@ -487,66 +493,163 @@ export default {
}
```
可以通过 [`markdown` 选项](../config/app-config#markdown)了解更多。
Please see [`markdown` options](/reference/site-config#markdown) for more details.
You can add `:line-numbers` / `:no-line-numbers` mark in your fenced code blocks to override the value set in config.
**Input**
````md
```ts {1}
// line-numbers is disabled by default
const line2 = 'This is line 2'
const line3 = 'This is line 3'
```
```ts:line-numbers {1}
// line-numbers is enabled
const line2 = 'This is line 2'
const line3 = 'This is line 3'
```
````
**Output**
```ts {1}
// line-numbers is disabled by default
const line2 = 'This is line 2'
const line3 = 'This is line 3'
```
```ts:line-numbers {1}
// line-numbers is enabled
const line2 = 'This is line 2'
const line3 = 'This is line 3'
```
## 导入代码片段 {#import-code-snippets}
## Import Code Snippets
你可以通过以下语法从现有文件中导入代码片段:
You can import code snippets from existing files via following syntax:
```md
<<< @/filepath
```
同时也支持[行高亮](#line-highlighting-in-code-blocks)
It also supports [line highlighting](#line-highlighting-in-code-blocks):
```md
<<< @/filepath{highlightLines}
```
**输入**
**Input**
```md
<<< @/snippets/snippet.js{2}
```
**代码文件**
**Code file**
<<< @/snippets/snippet.js
**输出**
**Output**
<<< @/snippets/snippet.js{2}
::: tip
`@` 相当于项目指定的源目录。默认情况下,它是 VitePress 项目根目录,当然也可以通过 `srcDir` 配置项配置。
The value of `@` corresponds to the source root. By default it's the VitePress project root, unless `srcDir` is configured.
:::
你也可以使用 [VS Code region](https://code.visualstudio.com/docs/editor/codebasics#_folding) 来导入仅包含代码文件的部分。也可以在文件路径后的 `#` 后面提供自定义区域名称:
You can also use a [VS Code region](https://code.visualstudio.com/docs/editor/codebasics#_folding) to only include the corresponding part of the code file. You can provide a custom region name after a `#` following the filepath:
**输入**
**Input**
```md
<<< @/snippets/snippet-with-region.js#snippet{1}
```
**代码文件**
**Code file**
<<< @/snippets/snippet-with-region.js
**输出**
**Output**
<<< @/snippets/snippet-with-region.js#snippet{1}
你还可以在大括号 (`{}`) 中指定语言:
You can also specify the language inside the braces (`{}`) like this:
```md
<<< @/snippets/snippet.cs{c#}
<!-- 指定 行高亮: -->
<!-- with line highlighting: -->
<<< @/snippets/snippet.cs{1,2,4-6 c#}
<!-- with line numbers: -->
<<< @/snippets/snippet.cs{1,2,4-6 c#:line-numbers}
```
This is helpful if source language cannot be inferred from your file extension.
## Code Groups
You can group multiple code blocks like this:
**Input**
````md
::: code-group
```js [config.js]
/**
* @type {import('vitepress').UserConfig}
*/
const config = {
// ...
}
export default config
```
这在无法从文件扩展名中推断出源语言会很有用。
```ts [config.ts]
import type { UserConfig } from 'vitepress'
const config: UserConfig = {
// ...
}
export default config
```
:::
````
**Output**
::: code-group
```js [config.js]
/**
* @type {import('vitepress').UserConfig}
*/
const config = {
// ...
}
export default config
```
```ts [config.ts]
import type { UserConfig } from 'vitepress'
const config: UserConfig = {
// ...
}
export default config
```
:::
You can also [import snippets](#import-code-snippets) in code groups:
@ -576,11 +679,11 @@ You can also [import snippets](#import-code-snippets) in code groups:
:::
## 包含其他 Markdown 文件 {#markdown-file-inclusion}
## Markdown File Inclusion
你可以通过下面的写法在 markdown 文件中引入其他的markdown 文件:
You can include a markdown file in another markdown file like this:
**输入**
**Input**
```md
# Docs
@ -590,7 +693,7 @@ You can also [import snippets](#import-code-snippets) in code groups:
<!--@include: ./parts/basics.md-->
```
**Part 文件** (`parts/basics.md`)
**Part file** (`parts/basics.md`)
```md
Some getting started stuff.
@ -600,7 +703,7 @@ Some getting started stuff.
Can be created using `.foorc.json`.
```
**等同于以下代码**
**Equivalent code**
```md
# Docs
@ -614,13 +717,13 @@ Some getting started stuff.
Can be created using `.foorc.json`.
```
::: warning 警告
注意,如果文件不存在,将不会抛出错误。因此,在使用此功能时,请确保按预期呈现内容。
::: warning
Note that this does not throw errors if your file is not present. Hence, when using this feature make sure that the contents are being rendered as expected.
:::
## 高级配置 {#advanced-configuration}
## Advanced Configuration
VitePress使用 [markdown-it](https://github.com/markdown-it/markdown-it) 作为Markdown 渲染器。上面的许多扩展是通过自定义插件实现的。你可以使用`vitepress/config.js`中的 `Markdown` 选项进一步自定义 `Markdown-It` 实例:
VitePress uses [markdown-it](https://github.com/markdown-it/markdown-it) as the Markdown renderer. A lot of the extensions above are implemented via custom plugins. You can further customize the `markdown-it` instance using the `markdown` option in `.vitepress/config.js`:
```js
const anchor = require('markdown-it-anchor')
@ -645,4 +748,4 @@ module.exports = {
}
```
通过[配置:应用全局配置](../config/app-config#markdown)查看可配置属性的完整列表。
See full list of configurable properties in [Config Reference: App Config](/reference/site-config#markdown).

@ -1,23 +1,23 @@
# 从 VitePress 0.x 迁移 {#migration-from-vitepress-0-x}
# Migration from VitePress 0.x
如果你来自 VitePress 0.x 版本,由于新功能和增强功能,会有一些重大更改。 请按照本指南了解如何将你的应用程序迁移到最新的 VitePress。
If you're coming from VitePress 0.x version, there're several breaking changes due to new features and enhancement. Please follow this guide to see how to migrate your app over to the latest VitePress.
## 应用全局配置 {#app-config}
## App Config
- 国际化功能尚未实现。
- The internationalization feature is not yet implemented.
## 主题配置 {#theme-config}
## Theme Config
- `sidebar` 选项改变了它的结构。
- `children` key现在命名为 `items`
- 顶级项目目前可能不包含 `link`。我们打算把它转回来。
- 删除了`repo`、`repoLabel`、`docsDir`、`docsBranch`、`editLinks`、`editLinkText`,以支持更灵活的 api。
- 要将带有图标的 GitHub 链接添加到导航,请使用[社交链接](./theme-nav#navigation-links)功能。
- 要添加“编辑此页面”功能,请使用[编辑链接](./theme-edit-link)功能。
- `lastUpdated` 选项现在分为 `config.lastUpdated``themeConfig.lastUpdatedText`
- `carbonAds.carbon` 更改为 `carbonAds.code`
- `sidebar` option has changed its structure.
- `children` key is now named `items`.
- Top level item may not contain `link` at the moment. We're planning to bring it back.
- `repo`, `repoLabel`, `docsDir`, `docsBranch`, `editLinks`, `editLinkText` are removed in favor of more flexible api.
- For adding GitHub link with icon to the nav, use [Social Links](/reference/default-theme-nav#navigation-links) feature.
- For adding "Edit this page" feature, use [Edit Link](/reference/default-theme-edit-link) feature.
- `lastUpdated` option is now split into `config.lastUpdated` and `themeConfig.lastUpdatedText`.
- `carbonAds.carbon` is changed to `carbonAds.code`.
## Frontmatter 配置 {#frontmatter-config}
## Frontmatter Config
- `home: true` 选项已更改为 `layout: home`。此外,还修改了许多与主页相关的设置以提供附加功能。详情请参阅[主页指南](./theme-home-page)。
- `footer` 选项移至 [`themeConfig.footer`](../config/theme-config#footer)。
- `home: true` option has changed to `layout: home`. Also, many Homepage related settings have been modified to provide additional features. See [Home Page guide](/reference/default-theme-home-page) for details.
- `footer` option is moved to [`themeConfig.footer`](/reference/default-theme-config#footer).

@ -1,30 +1,30 @@
# 从 VuePress 迁移 {#migration-from-vuepress}
# Migration from VuePress
## 配置 {#config}
## Config
### 侧边栏 {#sidebar}
### Sidebar
侧边栏不再从 frontmatter 中自动获取。 你可以[自行阅读 frontmatter](https://github.com/vuejs/vitepress/issues/572#issuecomment-1170116225) 来动态填充侧边栏。 [其他的工具方法](https://github.com/vuejs/vitepress/issues/96)将来可能会提供。
The sidebar is no longer automatically populated from frontmatter. You can [read the frontmatter yourself](https://github.com/vuejs/vitepress/issues/572#issuecomment-1170116225) to dynamically populate the sidebar. [Additional utilities for this](https://github.com/vuejs/vitepress/issues/96) may be provided in the future.
## Markdown
## Markdown
### 图片 {#images}
### Images
与 VuePress 不同在使用静态图片时VitePress 会根据你的配置自动处理这些 [`base`](./asset-handling#base-url)。
Unlike VuePress, VitePress handles [`base`](./asset-handling#base-url) of your config automatically when you use static image.
因此,现在你可以在没有 `img` 标签的情况下渲染图像。
Hence, now you can render images without `img` tag.
```diff
- <img :src="$withBase('/foo.png')" alt="foo">
+ ![foo](/foo.png)
```
::: warning 警告
对于动态图像,你仍然需要 `withBase`,如[基本 URL 指南](./asset-handling#base-url)中所示。
::: warning
For dynamic images you still need `withBase` as shown in [Base URL guide](./asset-handling#base-url).
:::
使用 `<img.*withBase\('(.*)'\).*alt="([^"]*)".*>` 正则表达式查找并替换为 `![$2]($1)``![](...)` 语法替换所有图像。
Use `<img.*withBase\('(.*)'\).*alt="([^"]*)".*>` regex to find and replace it with `![$2]($1)` to replace all the images with `![](...)` syntax.
---
更多请继续关注...
more to follow...

@ -0,0 +1,23 @@
# MPA Mode <Badge type="warning" text="experimental" />
MPA (Multi-Page Application) mode can be enabled via the command line via `vitepress build --mpa`, or via config through the `mpa: true` option.
In MPA mode, all pages are rendered without any JavaScript included by default. As a result, the production site will likely have a better initial visit performance score from audit tools.
However, due to the absence of SPA navigation, cross-page links will lead to full page reloads. Post-load navigations in MPA mode will not feel as instant as in SPA mode.
Also note that no-JS-by-default also means you are essentially using Vue purely as a server-side templating language - no event handlers will be attached in the browser, so there will be no interactivity. To load client-side JavaScript, you can do so by using the special `<script client>` tag (works in both `.md` and `.vue` files, but only in MPA mode):
```html
<script client>
document.querySelector('h1').addEventListener('click', () => {
console.log('client side JavaScript!')
})
</script>
# Hello
```
Client scripts in all theme components will be bundled together, while client script for a specific page will be split for that page only.
Notice that `<script client>` is **not evaluated as Vue component code**: it's processed as a plain JavaScript module. For this reason, MPA mode should only be used if your site requires absolutely minimal client-side interactivity.

@ -1,10 +1,12 @@
# 路由 {#routing}
---
outline: deep
---
VitePress 是基于文件系统的路由,这意味着源文件的目录结构与最终的 URL 相对应。你也可以自定义目录结构和 URL 的映射。阅读本页面,了解有关 VitePress 路由系统的一切。
# Routing
## 路由的基本用法 {#basic-routing}
## File-Based Routing
默认情况下VitePress 假设你的页面文件存储在项目根部。在这里你可以添加 markdown 文件,其名称为 URL 路径。例如,当你有以下目录结构时:
VitePress uses file-based routing, which means the generated HTML pages are mapped from the directory structure of the source Markdown files. For example, given the following directory structure:
```
.
@ -15,51 +17,71 @@ VitePress 是基于文件系统的路由,这意味着源文件的目录结构
└─ prologue.md
```
然后你可以通过以下 URL 访问这些页面。
The generated HTML pages will be:
```
index.md -> /
prologue.md -> /prologue.html
guide/index.md -> /guide/
getting-started.md -> /guide/getting-started.html
index.md --> /index.html (accessible as /)
prologue.md --> /prologue.html
guide/index.md --> /guide/index.html (accessible as /guide/)
guide/getting-started.md --> /guide/getting-started.html
```
正如你所看到的,目录结构与最终的 URL 相对应,就像从一个典型的网络服务器托管纯 HTML 一样。
The resulting HTML can be hosted on any web server that can serve static files.
## 改变根目录 {#changing-the-root-directory}
## Root and Source Directory
要改变你的页面文件的根目录,你可以把目录名称传给 `vitepress` 命令。例如,如果你想把你的页面文件存放在 `docs` 目录下,那么你应该运行 `vitepress dev docs` 命令。
There are two important concepts in the file structure of a VitePress project: the **project root** and the **source directory**.
### Project Root
Project root is where VitePress will try to look for the `.vitepress` special directory. The `.vitepress` directory is a reserved location for VitePress' config file, dev server cache, build output, and optional theme customization code.
When you run `vitepress dev` or `vitepress build` from the command line, VitePress will use the current working directory as project root. To specify a sub-directory as root, you will need to pass the relative path to the command. For example, if your VitePress project is located in `./docs`, you should run `vitepress dev docs`:
```
.
├─ docs
├─ docs # project root
│ ├─ .vitepress # config dir
│ ├─ getting-started.md
│ └─ index.md
└─ ...
```
```
```sh
vitepress dev docs
```
这将会映射到如下的 URL
This is going to result in the following source-to-HTML mapping:
```
docs/index.md -> /
docs/getting-started.md -> /getting-started.html
docs/index.md --> /index.html (accessible as /)
docs/getting-started.md --> /getting-started.html
```
你也可以在配置文件中通过 [srcDir](/config/app-config#srcdir) 选项自定义根目录。使用以下设置运行 `vitepress dev`,与运行 `vitepress dev docs` 命令的效果相同。
### Source Directory
Source directory is where your Markdown source files live. By default, it is the same as the project root. However, you can configure it via the [`srcDir`](/reference/site-config#srcdir) config option.
The `srcDir` option is resolved relative to project root. For example, with `srcDir: 'src'`, your file structure will look like this:
```ts
export default {
srcDir: './docs'
}
```
. # project root
├─ .vitepress # config dir
└─ src # source dir
├─ getting-started.md
└─ index.md
```
## 建立页面之间的链接 {#linking-between-pages}
The resulting source-to-HTML mapping:
在页面中添加链接时省略路径中的扩展名VitePress 将根据你的配置来处理扩展名。
```
src/index.md --> /index.html (accessible as /)
src/getting-started.md --> /getting-started.html
```
## Linking Between Pages
You can use both absolute and relative paths when linking between pages. Note that although both `.md` and `.html` extensions will work, the best practice is to omit file extensions so that VitePress can generate the final URLs based on your config.
```md
<!-- Do -->
@ -71,13 +93,13 @@ export default {
[Getting Started](/guide/getting-started.html)
```
了解更多关于页面链接和资源链接的信息,如图片链接,参见[资源处理](asset-handling)。
Learn more about linking to assets such images in [Asset Handling](asset-handling).
## 生成简洁的 URL {#generate-clean-url}
## Generating Clean URL
"简洁的 URL" 通常是指没有 `.html` 扩展名的 URL。比如我们使用 `example.com/path` 而不是 `example.com/path.html`
By default, VitePress resolves inbound links to URLs ending with `.html`. However, some users may prefer "Clean URLs" without the `.html` extension - for example, `example.com/path` instead of `example.com/path.html`.
默认情况下VitePress 生成最终的静态页面文件时,在每个文件中添加 `.html`扩展名。如果你想拥有简洁的 URL你可以只使用 `index.html` 文件来构造你的目录。
One way to achieve clean URLs is to structure your files using only `index.md` inside directories:
```
.
@ -88,17 +110,11 @@ export default {
└─ index.md
```
然而,你也可以通过设置 [`cleanUrls`](/config/app-config#cleanurls) 选项生成一个简洁的URL。
Some servers or hosting platforms (for example Netlify or Vercel) provide the ability to map a URL like `/foo` to `/foo.html` if it exists. If this feature is available to you, you can use the [`cleanUrls`](/reference/site-config#cleanurls) config option so that inbound links are always generated without the `.html` extension. When this option is enabled, VitePress' client-side router will also redirect to the clean URL when a visited URL ends with `.html`.
```ts
export default {
cleanUrls: true
}
```
## Route Rewrites
## 自定义映射 {#customize-the-mappings}
你可以自定义目录结构和 URL 之间的映射。当你有复杂的文件结构时,这很有用。例如,假设你有几个包,想把文档和源文件放在一起,像这样:
You can customize the mapping between the source directory structure and the generated pages. It's useful when you have a complex project structure. For example, let's say you have a monorepo with multiple packages, and would like to place documentations along with the source files like this:
```
.
@ -106,68 +122,216 @@ export default {
│ ├─ pkg-a
│ │ └─ src
│ │ ├─ pkg-a-code.ts
│ │ └─ pkg-a-code.md
│ │ └─ pkg-a-docs.md
│ └─ pkg-b
│ └─ src
│ ├─ pkg-b-code.ts
│ └─ pkg-b-code.md
│ └─ pkg-b-docs.md
```
并且你希望按如下方式生成 VitePress 页面。
And you want the VitePress pages to be generated like this:
```
packages/pkg-a/src/pkg-a-code.md -> /pkg-a/pkg-a-code.md
packages/pkg-b/src/pkg-b-code.md -> /pkg-b/pkg-b-code.md
packages/pkg-a/src/pkg-a-docs.md --> /pkg-a/index.html
packages/pkg-b/src/pkg-b-docs.md --> /pkg-b/index.html
```
可以像这样通过 [`rewrites`](/config/app-config#rewrites) 选项配置映射。
You can achieve this by configuring the [`rewrites`](/reference/site-config#rewrites) option like this:
```ts
// .vitepress/config.js
export default {
rewrites: {
'packages/pkg-a/src/pkg-a-code.md': 'pkg-a/pkg-a-code.md',
'packages/pkg-b/src/pkg-b-code.md': 'pkg-b/pkg-b-code.md'
'packages/pkg-a/src/pkg-a-docs.md': 'pkg-a/index.md',
'packages/pkg-b/src/pkg-b-docs.md': 'pkg-b/index.md'
}
}
```
`rewrites` 选项也可以有动态路由参数。在这个例子中,`package` 和 `src` 有固定的路径,在所有的页面上都相同,而且在你添加页面的时候,必须在你的配置中列出所有的页面,看起来这有点重复。所以你可以按下面的方法配置上述映射,并得到同样的结果。
The `rewrites` option also supports dynamic route parameters. In the above example, it would be verbose to list all the paths if you have many packages. Given that they all have the same file structure, you can simplify the config like this:
```ts
export default {
rewrites: {
'packages/:pkg/src/:page': ':pkg/:page'
'packages/:pkg/src/(.*)': ':pkg/index.md'
}
}
```
路由参数前缀为 `:` (e.g. `:pkg`)。参数的名称只是一个占位符,可以是任何东西。
The rewrite paths are compiled using the `path-to-regexp` package - consult [its documentation](https://github.com/pillarjs/path-to-regexp#parameters) for more advanced syntax.
另外你可能会在参数的末尾添加 `*` 以映射所有子目录。
:::warning Relative Links with Rewrites
```ts
When rewrites are enabled, **relative links should be based on the rewritten paths**. For example, in order to create a relative link from `packages/pkg-a/src/pkg-a-code.md` to `packages/pkg-b/src/pkg-b-code.md`, you should use:
```md
[Link to PKG B](../pkg-b/pkg-b-code)
```
:::
## Dynamic Routes
You can generate many pages using a single Markdown file and dynamic data. For example, you can create a `packages/[pkg].md` file that generates a corresponding page for every package in a project. Here, the `[pkg]` segment is a route **parameter** that differentiates each page from the others.
### Paths Loader File
Since VitePress is a static site generator, the possible page paths must be determined at build time. Therefore, a dynamic route page **must** be accompanied by a **paths loader file**. For `packages/[pkg].md`, we will need `packages/[pkg].paths.js` (`.ts` is also supported):
```
.
└─ packages
├─ [pkg].md # route template
└─ [pkg].paths.js # route paths loader
```
The paths loader should provide an object with a `paths` method as its default export. The `paths` method should return an array of objects with a `params` property. Each of these objects will generate a corresponding page.
Given the following `paths` array:
```js
// packages/[pkg].paths.js
export default {
rewrites: {
'packages/:pkg/src/:page*': ':pkg/:page*'
paths() {
return [
{ params: { pkg: 'foo' }},
{ params: { pkg: 'bar' }}
]
}
}
```
上述内容将创建如下映射。
The generated HTML pages will be:
```
packages/pkg-a/src/pkg-a-code.md -> /pkg-a/pkg-a-code.md
packages/pkg-b/src/folder/file.md -> /pkg-b/folder/file.md
.
└─ packages
├─ foo.html
└─ bar.html
```
::: warning 你需要在添加页面时重新启动服务器
目前VitePress 无法检测到映射目录中的页面添加情况。在开发模式下从目录中添加或删除文件时,你需要重新启动你的服务器。更新已经存在的文件则不需要。
:::
### Multiple Params
### 处理页面中的使用相对路径的链接 {#relative-link-handling-in-page}
A dynamic route can contain multiple params:
请注意,当启用 `rewrites`markdown 中的相对路径链接是相对于最终路径解析的。例如,为了创建从 `packages/pkg-a/src/pkg-a-code.md``packages/pkg-b/src/pkg-b-code.md` 的相对路径链接,你应该像下面这样定义链接。
**File Structure**
```
.
└─ packages
├─ [pkg]-[version].md
└─ [pkg]-[version].paths.js
```
**Paths Loader**
```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' }}
]
}
```
**Output**
```
.
└─ packages
├─ foo-1.0.0.html
├─ foo-2.0.0.html
├─ bar-1.0.0.html
└─ bar-2.0.0.html
```
### Dynamically Generating Paths
The paths loader module is run in Node.js and only executed during build time. You can dynamically generate the paths array using any data, either local or remote.
Generating paths from local files:
```js
import fs from 'fs'
export default {
paths() {
return fs
.readdirSync('packages')
.map((pkg) => {
return { params: { pkg }}
})
}
}
```
Generating paths from remote data:
```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
}
}
})
}
}
```
### Accessing Params in Page
You can use the params to pass additional data to each page. The Markdown route file can access the current page params in Vue expressions via the `$params` global property:
```md
[Link to PKG B](../pkg-b/pkg-b-code)
```
- package name: {{ $params.pkg }}
- version: {{ $params.version }}
```
You can also access the current page's params via the `[useData](/reference/runtime-api#usedata)` runtime API. This is available in both Markdown files and Vue components:
```vue
<script setup>
import { useData } from 'vitepress'
// params is a Vue ref
const { params } = useData()
console.log(params.value)
</script>
```
### Rendering Raw Content
Params passed to the page will be serialized in the client JavaScript payload, so you should avoid passing heavy data in params, for example raw Markdown or HTML content fetched from a remote CMS.
Instead, you can pass such content to each page using the `content` property on each path object:
```js
export default {
paths() {
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 // raw Markdown or HTML
}
})
}
}
}
```
Then, use the following special syntax to render the content as part of the Markdown file itself:
```md
<!-- @content -->
```

@ -1,22 +0,0 @@
# Carbon Ads
VitePress 内置了对 [Carbon Ads](https://www.carbonads.net/) 的原生支持。通过在配置中定义Carbon Ads凭证VitePress将在页面上显示广告。
```js
export default {
themeConfig: {
carbonAds: {
code: 'your-carbon-code',
placement: 'your-carbon-placement'
}
}
}
```
这些值用于调用 carbon CDN 脚本,如下所示。
```js
`//cdn.carbonads.com/carbon.js?serve=${code}&placement=${placement}`
```
如需了解有关 Carbon Ads 配置的更多信息,请访问 [Carbon Ads 站点](https://www.carbonads.net/)。

@ -1,28 +0,0 @@
# 编辑链接 {#edit-link}
编辑链接可以显示链接以编辑 Git 管理服务 (例如 GitHub 或 GitLab) 上的页面。 可以通过 `themeConfig.editLink` 选项配置来启用。
```js
export default {
themeConfig: {
editLink: {
pattern: 'https://github.com/vuejs/vitepress/edit/main/docs/:path'
}
}
}
```
`pattern` 选项定义了链接的 URL 结构,`:path` 将被页面路径替换。
默认情况下,这将在文档页面底部添加链接文本“编辑此页面”。你可以通过定义 `text` 选项来自定义此文本。
```js
export default {
themeConfig: {
editLink: {
pattern: 'https://github.com/vuejs/vitepress/edit/main/docs/:path',
text: 'Edit this page on GitHub'
}
}
}
```

@ -1,26 +0,0 @@
# 页脚 {#footer}
配置 `themeConfig.footer` 可以使 VitePress 在页面底部展示全局的页脚。
```ts
export default {
themeConfig: {
footer: {
message: 'Released under the MIT License.',
copyright: 'Copyright © 2019-present Evan You'
}
}
}
```
```ts
export interface Footer {
// The message shown rigth before copyright.
message?: string
// The actual copyright text.
copyright?: string
}
```
注意,当[侧边栏](./theme-sidebar)可见时,不会显示页脚。

@ -1,116 +0,0 @@
# 主页
VitePress 默认主题提供主页布局,你也可以在 [本站主页](../) 上看到使用的主页布局。 你可以通过在任何页面通过 [frontmatter](./frontmatter) 指定 `layout: home` 使用它。
```yaml
---
layout: home
---
```
但是,仅此选项不会有太大作用。 你可以通过设置额外的其他选项 (例如 `hero``features`) 将几个不同的预模板“部分”添加到主页。
## Hero 部分
Hero 部分位于主页的顶部。 以下是配置 Hero 部分的方法。
```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 {
// `text' 的字符串所示。带有品牌颜色,通常会很短,例如项目名称。
name?: string
// hero 部分的文本。这将被定义成`h1`标签
text: string
// Tagline 会展示在 `text` 下面。
tagline?: string
// action 按钮显示在 hero 区域。
actions?: HeroAction[]
}
interface HeroAction {
// 按钮的的主题颜色,默认为 `brand`
theme?: 'brand' | 'alt'
// 按钮的内容。
text: string
// 按钮链接。
link: string
}
```
### 自定义名字颜色 {#customizing-the-name-color}
VitePress 使用品牌颜色 (`--vp-c-brand`) 作为 `name`。 但是,你可以通过覆盖 `--vp-home-hero-name-color` 变量来自定义此颜色。
```css
:root {
--vp-home-hero-name-color: blue;
}
```
你也可以通过组合 `--vp-home-hero-name-background` 来进一步自定义它,以赋予 `name` 渐变颜色。
```css
:root {
--vp-home-hero-name-color: transparent;
--vp-home-hero-name-background: -webkit-linear-gradient(120deg, #bd34fe, #41d1ff);
}
```
## Features 部分 {#features-section}
在 Features 部分,你可以在 hero 部分之后列出你想要显示的任意数量的功能。 要配置它,请在 `formatter` 中配置 `features`
```yaml
---
layout: home
features:
- icon: ⚡️
title: Vite, The DX that can't be beat
details: Lorem ipsum...
- icon: 🖖
title: Power of Vue meets Markdown
details: Lorem ipsum...
- icon: 🛠️
title: Simple and minimal, always
details: Lorem ipsum...
---
```
```ts
interface Feature {
// 在 feature 框里展示 icon目前只支持 emoji
icon?: string
// feature 标题
title: string
// feature 详情
details: string
}
```

@ -1,20 +0,0 @@
# 最后更新 {#last-updated}
最后内容的更新时间将显示在页面的右下角。要启用它,请在你的配置中添加 `lastUpdated` 选项。
## 页面配置 {#page-configuration}
添加 `lastUpdated` 选项到配置中去。
```js
export default {
lastUpdated: true
}
```
## Frontmatter 配置 {#frontmatter-configuration}
如果你想隐藏最后更新的文本,请对 `lastUpdated` 选项设置为 false。
```yaml
---
lastUpdated: false
---
```

@ -1,37 +0,0 @@
# Layout
你可以通过在页面 [frontmatter](./frontmatter) 中设置 `layout` 选项选择页面布局。有 3 个布局选项,`doc`、`page` 和 `home`。 如果未指定任何内容,则该页面被视为文档页面。
```yaml
---
layout: doc
---
```
## Doc 布局 {#doc-layout}
`doc` 是默认布局,它将整个 Markdown 内容样式化为“文档”外观。它的工作原理是将整个内容包装在 `vp-doc` css 类中,并将样式应用于它下面的元素。
几乎所有通用元素,例如 `p``h2` 都具有特殊样式。 因此,请记住,如果你在 Markdown 内容中添加任何自定义 HTML这些元素也会受到这些样式的影响。
同时还提供下面列出的文档特定功能。这些功能仅在此布局中生效。
- 编辑链接
- 上一页/下一页链接
- 概述
- [Carbon Ads](./theme-carbon-ads)
## Page 布局 {#page-layout}
选项 `page` 被视为“空白页”。 Markdown 仍然会被解析,并且所有 [Markdown 扩展](./markdown)与 `doc` 布局同样生效,但它不会有任何默认样式。
page 布局可在 VitePress 主题不会影响标签的情况下让你自行设计所有内容。当你要创建自己的自定义页面时,这很有用。
注意,即使在此布局中,如果页面具有匹配的侧边栏配置,侧边栏仍会显示。
## Home 布局 {#home-layout}
选项 `home` 将生成模板化的“主页”。 在此布局中,你可以设置额外的选项,例如 `hero``features`,以进一步自定义内容。请访问[主题:主页](./theme-home-page)了解更多详情。
## No 布局 {#no-layout}
如果你不想要任何布局,你可以通过在 frontmatter 中设置 `layout: false`。如果你想要一个完全可定制的登录页面 (默认情况下没有任何侧边栏、导航栏或页脚),这个选项很有用。

@ -1,161 +0,0 @@
# 侧边栏 {#sidebar}
侧边栏是文档的主要导航块。可以在 `themeConfig.sidebar` 中配置侧边栏菜单。
```js
export default {
themeConfig: {
sidebar: [
{
text: 'Guide',
items: [
{ text: 'Introduction', link: '/introduction' },
{ text: 'Getting Started', link: '/getting-started' },
...
]
}
]
}
}
```
## 基本使用 {#the-basics}
侧边栏菜单的最简单形式是传入一个链接数组。第一级项目定义了侧边栏部分。它应该包含 `text`,即该部分的标题,以及 `items`,即实际的导航链接。
```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' },
...
]
}
]
}
}
```
每个 `link` 都应该指定以 `/` 开头的实际文件的路径。如果在链接末尾添加斜杠,它将显示相应目录的`index.md`。
```js
export default {
themeConfig: {
sidebar: [
{
text: 'Guide',
items: [
// This shows `/guide/index.md` page.
{ text: 'Introduction', link: '/guide/' }
]
}
]
}
}
```
## 多个侧边栏 {#multiple-sidebars}
你可能会根据页面路径显示不同的侧边栏。例如,如本站点所示,你可能希望在文档中创建单独的内容部分,例如“指南”页面和“配置”页面。
为此,首先将你的页面放到所在的目录中:
```
.
├─ guide/
│ ├─ index.md
│ ├─ one.md
│ └─ two.md
└─ config/
├─ index.md
├─ three.md
└─ four.md
```
然后,更新配置以定义每个部分的侧边栏,不同的是,这次配置的是一个对象而不是数组。
```js
export default {
themeConfig: {
sidebar: {
// 当用户在 `指南` 目录页面下将会展示这个侧边栏
'/guide/': [
{
text: 'Guide',
items: [
// This shows `/guide/index.md` page.
{ text: 'Index', link: '/guide/' }, // /guide/index.md
{ text: 'One', link: '/guide/one' }, // /guide/one.md
{ text: 'Two', link: '/guide/two' } // /guide/two.md
]
}
],
// 当用户在 `配置` 目录页面下将会展示这个侧边栏
'/config/': [
{
text: 'Config',
items: [
// This shows `/config/index.md` page.
{ text: 'Index', link: '/config/' }, // /config/index.md
{ text: 'Three', link: '/config/three' }, // /config/three.md
{ text: 'Four', link: '/config/four' } // /config/four.md
]
}
]
}
}
}
```
## 可折叠的侧边栏组 {#collapsible-sidebar-groups}
通过向侧边栏组添加 `collapsible` 选项,它会显示一个切换按钮来隐藏或显示子菜单。
```js
export default {
themeConfig: {
sidebar: [
{
text: 'Section Title A',
collapsible: true,
items: [...]
},
{
text: 'Section Title B',
collapsible: true,
items: [...]
}
]
}
}
```
默认情况下,所有侧边栏都是展开的。如果你希望它们在初始页面加载时关闭,请将 `collapsed` 选项设置为 `true`
```js
export default {
themeConfig: {
sidebar: [
{
text: 'Section Title A',
collapsible: true,
collapsed: true,
items: [...]
}
]
}
}
```

@ -1,44 +1,75 @@
# Markdown 中使用 Vue {#using-vue-in-markdown}
# Using Vue in Markdown
在 VitePress 中,每个 markdown 文件都被编译成 HTML然后其作为 Vue 单文件组件处理。这意味着你可以在 markdown 中使用所有的 Vue 功能包括动态模板、Vue 组件或通过添加 `<script>` 标签使用 Vue 组件逻辑。
In VitePress, each Markdown file is compiled into HTML and then processed as a [Vue Single-File Component](https://vuejs.org/guide/scaling-up/sfc.html). This means you can use any Vue features inside the Markdown, including dynamic templating, using Vue components, or arbitrary in-page Vue component logic by adding a `<script>` tag.
同样重要的是要知道 VitePress 利用 Vue 3 的编译器来自动检测 markdown 中的纯静态的部分。静态内容被优化为独立的节点,从而减少页面的 JS 的开销。在客户端渲染数据期间,它们也会被跳过。简而言之,你需要额外处理的只有页面上的动态部分。
It's worth noting that VitePress leverages Vue's compiler to automatically detect and optimize the purely static parts of the Markdown content. Static contents are optimized into single placeholder nodes and eliminated from the page's JavaScript payload for initial visits. They are also skipped during client-side hydration. In short, you only pay for the dynamic parts on any given page.
## 模板语法 {#templating}
## Templating
### 插值 {#interpolation}
### Interpolation
每个 Markdown 文件首先编译成 HTML然后作为 Vue 组件传递到 Vite 处理。这意味着你可以在文本中使用 Vue 风格的插值:
Each Markdown file is first compiled into HTML and then passed on as a Vue component to the Vite process pipeline. This means you can use Vue-style interpolation in text:
**输入**
**Input**
```md
{{ 1 + 1 }}
```
**输出**
**Output**
<div class="language-text"><pre><code>{{ 1 + 1 }}</code></pre></div>
### 指令 {#directives}
### Directives
指令同样可用:
Directives also work (note that by design, raw HTML is also valid in Markdown):
**输入**
**Input**
```html
<span v-for="i in 3">{{ i }}</span>
```
**输出**
**Output**
<div class="language-text"><pre><code><span v-for="i in 3">{{ i }} </span></code></pre></div>
### 获取站点和页面数据 {#access-to-site-page-data}
## `<script>` and `<style>`
你可以在 `<script>` 里使用 [`useData` 辅助函数](/api/#usedata) 并在页面里绑定数据。
Root-level `<script>` and `<style>` tags in Markdown files work just like they do in Vue SFCs, including `<script setup>`, `<style module>`, etc. The main difference here is that there is no `<template>` tag: all other root-level content is Markdown. Also note that all tags should be placed **after** the frontmatter:
**输入**
```html
---
hello: world
---
<script setup>
import { ref } from 'vue'
const count = ref(0)
</script>
## Markdown Content
The count is: {{ count }}
<button :class="$style.module" @click="count++">Increment</button>
<style module>
.button {
color: red;
font-weight: bold;
}
</style>
```
:::warning Avoid `<style scoped>` in Markdown
When used in Markdown, `<style scoped>` requires adding special attributes to every element on the current page, which will significantly bloat the page size. `<style module>` is preferred when locally-scoped styling is needed in a page.
:::
You also have access to VitePress' runtime APIs such as the [`useData` helper](/reference/runtime-api#usedata), which provides access to current page's metadata:
**Input**
```html
<script setup>
@ -50,41 +81,24 @@ const { page } = useData()
<pre>{{ page }}</pre>
```
**输出**
**Output**
```json
{
"path": "/using-vue.html",
"title": "Using Vue in Markdown",
"frontmatter": {}
"frontmatter": {},
...
}
```
## 转义 {#escaping}
默认情况下,栅栏式代码块会自动使用 `v-pre` 包装。要在内联代码片段或纯文本中展示 mustaches 或特定的 Vue 语法,你需要使用 `v-pre` 自定义容器包装一个段落:
**输入**
```md
::: v-pre
`{{ This will be displayed as-is }}`
:::
```
**输出**
## Using Components
::: v-pre
`{{ This will be displayed as-is }}`
:::
## 使用组件 {#using-components}
当你需要更大的灵活性时VitePress 支持使用你自己的 Vue 组件扩展你的创作工具箱。
You can import and use Vue components directly in Markdown files.
### 在 markdown 中导入组件 {#importing-components-in-markdown}
### Importing in Markdown
如果你的组件仅在少数地方使用,推荐的使用方法是在使用它的文件中导入组件。
If a component is only used by a few pages, it's recommended to explicitly import them where they are used. This allows them to be properly code-split and only loaded when the relevant pages are shown:
```md
<script setup>
@ -102,53 +116,85 @@ This is a .md using a custom component
...
```
### 在主题中注册全局组件 {#registering-global-components-in-the-theme}
### Registering Components Globally
如果要在文档中的多个页面中使用组件,则可以在主题中全局注册它们 (或作为默认 VitePress 主题扩展的一部分)。查看[自定义指南](./customization-intro)了解更多信息。
If a component is going to be used on most of the pages, they can be registered globally by customizing the Vue app instance. See relevant section in [Extending Default Theme](/guide/extending-default-theme#registering-global-components) for an example.
`.vitepress/theme/index.js` 中,`enhanceApp` 函数接收 Vue `app` 实例,因此你可以在常规的 Vue 应用程序中 [注册组件](https://vuejs.org/guide/components/registration.html) 。
::: warning IMPORTANT
Make sure a custom component's name either contains a hyphen or is in PascalCase. Otherwise, it will be treated as an inline element and wrapped inside a `<p>` tag, which will lead to hydration mismatch because `<p>` does not allow block elements to be placed inside it.
:::
```js
import DefaultTheme from 'vitepress/theme'
### Using Components In Headers <ComponentInHeader />
export default {
...DefaultTheme,
enhanceApp({ app }) {
app.component('VueClickAwayExample', VueClickAwayExample)
}
}
```
You can use Vue components in the headers, but note the difference between the following syntaxes:
然后就可以在 markdown 文件里使用组件:
| Markdown | Output HTML | Parsed Header |
| ------------------------------------------------------- | ----------------------------------------- | ------------- |
| <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/>` |
The HTML wrapped by `<code>` will be displayed as-is; only the HTML that is **not** wrapped will be parsed by Vue.
::: tip
The output HTML is accomplished by [Markdown-it](https://github.com/Markdown-it/Markdown-it), while the parsed headers are handled by VitePress (and used for both the sidebar and document title).
:::
## Escaping
You can escape Vue interpolations by wrapping them in a `<span>` or other elements with the `v-pre` directive:
**Input**
```md
# Vue Click Away
This <span v-pre>{{ will be displayed as-is }}</span>
```
**Output**
<div class="escape-demo">
<p>This <span v-pre>{{ will be displayed as-is }}</span></p>
</div>
Alternatively, you can wrap the entire paragraph in a `v-pre` custom container:
<VueClickAwayExample />
```md
::: v-pre
{{ This will be displayed as-is }}`
:::
```
::: warning 重要
确保自定义组件的名称包含连字符或使用 PascalCase (大驼峰拼写)。否则,它将被视为内联元素并包裹在 `<p>` 标签中,这将会导致 HTML 渲染紊乱,因为 HTML 标准规定, `<p>` 标签中不允许放置任何块级元素。
**Output**
<div class="escape-demo">
::: v-pre
{{ This will be displayed as-is }}
:::
### 在标题中使用组件 <ComponentInHeader /> {#using-components-in-headers}
</div>
你可以在标题中使用 Vue 组件,但请注意以下语法之间的区别:
## Unescape in Code Blocks
| Markdown | Output HTML | Parsed Header |
| ------------------------------------------------------- | ----------------------------------------- | ------------- |
| <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/>` |
By default, all fenced code blocks are automatically wrapped with `v-pre`, so no Vue syntax will be processd inside. To enable Vue-style interpolation inside fences, you can append the language with the `-vue` suffix, e.g. `js-vue`:
`<code>` 包裹的 HTML 将按原样显示;只有**未**包裹 `<code>` 的 HTML 才会被 Vue 解析。
**Input**
::: tip
输出 HTML 由 [markdown-it](https://github.com/markdown-it/markdown-it) 完成,而解析的标题由 VitePress 处理(并用于侧边栏和文档标题)。
:::
````md
```js-vue
Hello {{ 1 + 1 }}
```
````
## 使用 CSS 预处理器 {#using-css-pre-processors}
**Output**
VitePress 对 CSS 预处理器有[内置支持](https://vitejs.dev/guide/features.html#css-pre-processors)`.scss`、`.sass`、`.less` `.styl``.stylus` 文件。 不需要为它们安装 Vite 特定的插件,但必须安装相应的预处理器:
```js-vue
Hello {{ 1 + 1 }}
```
## Using CSS Pre-processors
VitePress has [built-in support](https://vitejs.dev/guide/features.html#css-pre-processors) for CSS pre-processors: `.scss`, `.sass`, `.less`, `.styl` and `.stylus` files. There is no need to install Vite-specific plugins for them, but the corresponding pre-processor itself must be installed:
```
# .scss and .sass
@ -161,7 +207,7 @@ npm install -D less
npm install -D stylus
```
然后就可以在 Markdown 和主题组件中使用:
Then you can use the following in Markdown and theme components:
```vue
<style lang="sass">
@ -170,44 +216,11 @@ npm install -D stylus
</style>
```
## 脚本和样式提升 {#script-style-hoisting}
有时,你可以只想在当前页面应用一些 JavaScript 或者 CSS在这种情况下你可以直接在 Markdown 文件中使用原生的 `<script>` 或者 `<style>` 标签,它们将会从编译后的 HTML 文件中提取出来,并作为生成的 Vue 单文件组件的`<script>`和 `<style>` 标签:
<p class="demo" :class="$style.example"></p>
<style module>
.example {
color: #41b883;
}
</style>
<script>
import ComponentInHeader from '../../components/ComponentInHeader.vue'
export default {
props: ['slot-key'],
components: { ComponentInHeader },
mounted () {
document.querySelector(`.${this.$style.example}`)
.textContent = 'This is rendered by inline script and styled by inline CSS'
}
}
</script>
## 内置的组件 {#built-in-components}
VitePress 提供了内置的 Vue 组件,例如 `ClientOnly``OutboundLink`,查看[全局组件指南](/api/) 了解更多信息。
**参见:**
## Browser API Access Restrictions
- [在标题中使用组件](#using-components-in-headers)
Because VitePress applications are server-rendered in Node.js when generating static builds, any Vue usage must conform to the [universal code requirements](https://vuejs.org/guide/scaling-up/ssr.html). In short, make sure to only access Browser / DOM APIs in `beforeMount` or `mounted` hooks.
## 浏览器 API 的访问限制 {#browser-api-access-restrictions}
由于 VitePress 应用在生成静态构建时在 Node.js 中进行服务器渲染,因此任何 Vue 使用都必须符合[通用代码要求](https://vuejs.org/guide/scaling-up/ssr.html)。 简而言之,确保只在 `beforeMount``mounted` 钩子中访问浏览器以及 DOM API。
如果你正在使用不支持 SSR 的组件 (例如,包含自定义指令),你可以将它们包装在 `ClientOnly` 组件中。
If you are using or demoing components that are not SSR-friendly (for example, contain custom directives), you can wrap them inside the built-in `<ClientOnly>` component:
```md
<ClientOnly>
@ -215,7 +228,7 @@ VitePress 提供了内置的 Vue 组件,例如 `ClientOnly` 和 `OutboundLink`
</ClientOnly>
```
注意,这不会修复**在导入时**访问浏览器 API 的组件或库。 要在导入时使用浏览器环境的代码,你需要在适当的生命周期挂钩中动态导入它们:
Note this does not fix components or libraries that access Browser APIs **on import**. To use code that assumes a browser environment on import, you need to dynamically import them in proper lifecycle hooks:
```vue
<script>
@ -229,7 +242,7 @@ export default {
</script>
```
如果要使用 `export default` 导出的Vue 组件,你可以这样子动态注册:
If your module `export default` a Vue component, you can register it dynamically:
```vue
<template>
@ -256,6 +269,38 @@ export default {
</script>
```
**参见:**
**Also see:**
- [Vue.js > Dynamic Components](https://vuejs.org/guide/essentials/component-basics.html#dynamic-components)
## Using Teleports
Vitepress currently has SSG support for teleports to body only. For other targets, you can wrap them inside the built-in `<ClientOnly>` component or inject the teleport markup into the correct location in your final page HTML through [`postRender` hook](/reference/site-config#postrender).
<ModalDemo />
- [Vue.js > 动态组件](https://cn.vuejs.org/guide/essentials/component-basics.html#dynamic-components)
::: details
<<< @/components/ModalDemo.vue
:::
```md
<ClientOnly>
<Teleport to="#modal">
<div>
// ...
</div>
</Teleport>
</ClientOnly>
```
<script setup>
import ModalDemo from '../components/ModalDemo.vue'
</script>
<style>
.escape-demo {
border: 1px solid var(--vp-c-border);
border-radius: 8px;
padding: 0 20px;
}
</style>

Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

@ -1,6 +1,26 @@
# What is VitePress?
VitePress is a [Static Site Generator](https://en.wikipedia.org/wiki/Static_site_generator) (SSG). It is designed for building performant content-centric websites, such as this documentation you are reading right now. It also powers the documentation for [Vue.js](https://vuejs.org/), [Vite](https://vitejs.dev/), and many more<!-- TODO: showcase page? -->. In a nutshell, VitePress takes your source content written in [Markdown](https://en.wikipedia.org/wiki/Markdown), applies a theme to it, and generates a directory of static HTML pages (and necessary asset files) that can be easily deployed anywhere.
VitePress is a [Static Site Generator](https://en.wikipedia.org/wiki/Static_site_generator) (SSG) designed for building fast, content-centric websites. In a nutshell, VitePress takes your source content written in [Markdown](https://en.wikipedia.org/wiki/Markdown), applies a theme to it, and generates static HTML pages that can be easily deployed anywhere.
<div class="tip custom-block" style="padding-top: 8px">
Just want to try it out? Skip to the [Quickstart](./getting-started).
</div>
## Use Cases
- **Documentation**
VitePress ships with a default theme designed for technical documentation, especially those that need to embed interactive demos. It powers this page you are reading right now, along with the documentation for [Vite](https://vitejs.dev/), [Pinia](https://pinia.vuejs.org/), [VueUse](https://vueuse.org/), [Mermaid](https://mermaid.js.org/), [Wikimedia Codex](https://doc.wikimedia.org/codex/latest/), and many more.
The [official Vue.js documentation](https://vuejs.org/) is also based on VitePress, but uses a custom theme shared between multiple translations.
- **Blogs, Portfolios, and Marketing Sites**
VitePress supports [fully customized themes](/guide/custom-theme), with the developer experience of a standard Vite + Vue application. Being built on Vite also means you can directly leverage Vite plugins from its rich ecosystem. In addition, VitePress provides flexible APIs to [load data](/guide/data-loading) (local or remote) and [dynamically generate routes](/guide/routing#dynamic-routes). You can use it to build almost anything as long as the data can be determined at build time.
The official [Vue.js blog](https://blog.vuejs.org/) is a simple blog that generates its index page based on local content.
## Developer Experience
@ -18,7 +38,7 @@ Unlike many traditional SSGs, a website generated by VitePress is in fact a [Sin
- **Fast Initial Load**
The initial visit to any page will be served the static, pre-rendered HTML for maximum loading speed, together with a JavaScript bundle that turns the page into a Vue SPA ("hydration"). The hydration process is extremely fast: on [PageSpeed Insights](https://pagespeed.web.dev/), typical VitePress sites achieve near-perfect performance scores even on low-end mobile devices with a slow network.
The initial visit to any page will be served the static, pre-rendered HTML for blazing fast loading speed and optimal SEO. The page then loads a JavaScript bundle that turns the page into a Vue SPA ("hydration"). The hydration process is extremely fast: on [PageSpeed Insights](https://pagespeed.web.dev/report?url=https%3A%2F%2Fvitepress.vuejs.org%2F), typical VitePress sites achieve near-perfect performance scores even on low-end mobile devices with a slow network.
- **Fast Post-load Navigation**
@ -28,14 +48,6 @@ Unlike many traditional SSGs, a website generated by VitePress is in fact a [Sin
To be able to hydrate the dynamic Vue parts embedded inside static Markdown, each Markdown page is processed as a Vue component and compiled into JavaScript. This may sound inefficient, but the Vue compiler is smart enough to separate the static and dynamic parts, minimizing both the hydration cost and payload size. For the initial page load, the static parts are automatically eliminated from the JavaScript payload and skipped during hydration.
## Theming & Extensibility
VitePress ships with a feature-rich default theme designed for documentation purposes. It allows you to spin up a beautiful documentation site like this one with minimal effort, and doesn't require any Vue-specific knowledge.
VitePress also supports fully customized themes with the developer experience of a standard Vite + Vue application. Being built on Vite also means you can directly leverage Vite plugins from its rich ecosystem. This makes VitePress an ideal choice for building sites that is content-centric but also requires non-trivial interactivity. The [Vue.js documentation](https://github.com/vuejs/docs) is a good example of such customization.
And of course, you can use it to build a blog! The [official Vue.js blog](https://github.com/vuejs/blog) is also built with VitePress.
## What About VuePress?
VitePress is the spiritual successor of VuePress. The original VuePress was based on Vue 2 and webpack. With Vue 3 and Vite under the hood, VitePress provides significantly better DX, better production performance, a more polished default theme, and a more flexible customization API.

@ -7,7 +7,7 @@ titleTemplate: 由 Vite 和 Vue 驱动的静态站点生成器
hero:
name: VitePress
text: 由 Vite 和 Vue 驱动的静态站点生成器
tagline: 简单、强大、性能极佳。就是你想要的现代 SSG 框架!
tagline: 简单、强大、快速。就是你想要的现代 SSG 框架!
actions:
- theme: brand
text: 认识 VitePress
@ -17,12 +17,22 @@ hero:
link: https://github.com/vuejs/vitepress
features:
- title: Vite无可比拟的开发体验
details: 感受 Vite 的速度吧!不论应用程序大小如何,服务启动和 HMR 都是十分迅速的。
- title: 简单易用是首要的设计理念
details: 内容构建是以 Markdown 为中心的,它旨在帮助你专注于编写和以最少的配置进行部署。
- title: 由 Vue 和 Markdown 驱动
details: 在 Markdown 中使用 Vue 的所有特性的丰富内容,同时能够使用 Vue 自定义站点。
- title: 是静态的,但也是动态的
details: 真正的 SSG + SPA 构建。加载的是静态页面,但依然可以以 100% 的交互性吸引用户。
---
- icon: 📝
title: 专注内容
details: 只需 Markdown 即可轻松创建美观的文档站点。
- icon:
src: vite.svg
width: 10
height: 10
title: 享受 Vite 无可比拟的体验
details: 服务器即时启动,闪电般的热更新,还可以使用基于 Vite 生态的插件。
- icon:
src: vue.svg
width: 10
height: 10
title: 使用 Vue 自定义
details: 直接在 Markdown 中使用 Vue 语法和组件,或者使用 Vue 组件构建自定义主题。
- icon: 🚀
title: 速度真的很快!
details: 采用静态 HTML 实现快速的页面初次加载,使用客户端路由实现快速的页面切换导航。
---

@ -0,0 +1,74 @@
# 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 (default: `.vitepress/dist`) (`string`) |
| `--minify [minifier]` | Enable/disable minification, or specify minifier to use (default: `"esbuild"`) (`boolean \| "terser" \| "esbuild"`) |
| `--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
```

@ -1,10 +1,10 @@
# 徽章 {#badge}
# 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}
## Usage
你可以使用全局生效的 `Badge` 组件:
You may use the `Badge` component which is globally available.
```html
### Title <Badge type="info" text="default" />
@ -13,26 +13,26 @@
### 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" />
## 自定义 Children {#custom-children}
## Custom Children
`<Badge>` 接受 `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>
### Title <Badge type="info">custom element</Badge>
## 自定义颜色 {#customize-type-color}
## Customize Type Color
你可以通过覆盖 css 变量来定制徽章的 `background-color`。以下是默认值。
You can customize the `background-color` of badges by overriding css variables. The following are the default values:
```css
:root {
@ -70,7 +70,7 @@
## `<Badge>`
`<Badge>` 组件接受下面的 props
`<Badge>` component accepts following props:
```ts
interface Props {

@ -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/).

@ -1,6 +1,6 @@
# 主题配置 {#theme-config}
# Default Theme Config
主题配置可让你自定义主题。你可以通过将 `themeConfig` 键添加到配置文件来定义主题配置。
Theme config lets you customize your theme. You can define theme config via the `themeConfig` option in the config file:
```ts
export default {
@ -17,19 +17,19 @@ export default {
}
```
这里描述了 VitePress 默认主题的设置。如果你使用的是其他人创建的自定义主题,这些设置可能没有任何效果,或者可能表现不同。
**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
- 类型:`boolean`
- Type: `boolean`
改变语言环境意味着,`zh` 将 URL 从 `/foo` (or `/en/foo/`) 变成 `/zh/foo`。将 `themeConfig.i18nRouting` 设置为 `false` 可以禁用这一特性。
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
- 类型:`ThemeableImage`
- Type: `ThemeableImage`
显示在导航栏中的 logo 文件,位于站点标题之前。接受路径字符串或包含明亮或黑暗模式不同 logo 的对象。
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 {
@ -48,9 +48,9 @@ type ThemeableImage =
## siteTitle
- 类型:`string | false`
- Type: `string | false`
你可以自定义此项以替换导航中的默认站点标题 (应用配置中的 `title`)。当设置为 `false` 时,导航中的标题将被禁用。这在当你的 `logo` 已经包含网站标题文本时很有用。
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 {
@ -62,9 +62,9 @@ export default {
## nav
- 类型:`NavItem`
- Type: `NavItem`
导航菜单项的配置。你可以在[主题: 导航栏](../guide/theme-nav#navigation-links)中了解更多详情。
The configuration for the nav menu item. More details in [Default Theme: Nav](./default-theme-nav#navigation-links).
```js
export default {
@ -91,12 +91,13 @@ interface NavItemWithLink {
text: string
link: string
activeMatch?: string
target?: string
rel?: string
}
interface NavItemChildren {
text?: string
items: NavItemWithLink[]
activeMatch?: string
}
interface NavItemWithChildren {
@ -108,9 +109,9 @@ interface NavItemWithChildren {
## sidebar
- 类型:`Sidebar`
- Type: `Sidebar`
侧边栏菜单项的配置。你可以在[主题: 侧边栏](../guide/theme-sidebar)了解更多详情。
The configuration for the sidebar menu item. More details in [Default Theme: Sidebar](./default-theme-sidebar).
```js
export default {
@ -130,48 +131,66 @@ export default {
```
```ts
type Sidebar = SidebarGroup[] | SidebarMulti
export type Sidebar = SidebarItem[] | SidebarMulti
interface SidebarMulti {
[path: string]: SidebarGroup[]
export interface SidebarMulti {
[path: string]: SidebarItem[]
}
interface SidebarGroup {
text: string
items: SidebarItem[]
collapsible?: boolean
collapsed?: boolean
}
export type SidebarItem = {
/**
* The text label of the item.
*/
text?: string
interface SidebarItem {
text: string
link: 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
}
```
## aside
- Type: `boolean`
- Default: `true`
Setting this value to `false` prevents rendering of aside container.
## outline
- 类型:`number | [number, number] | 'deep' | false`
- 默认值:`2`
- Type: `number | [number, number] | 'deep' | false`
- Default: `2`
纲要中显示的标题的级别。你可以通过传递一个数字来指定一个特定的级别,也可以通过传递一个包含底限和上限的元组来提供一个级别范围。当传递等于 `[2, 6]``'deep'` 时,除了 `h1` 之外,所有的标题级别都显示在大纲中。可以设置 `false` 来隐藏轮廓。
The levels of header to display in the outline. You can specify a particular level by passing a number, or you can provide a level range by passing a tuple containing the bottom and upper limits. When passing `'deep'` which equals `[2, 6]`, all header levels are shown in the outline except `h1`. Set `false` to hide outline.
## outlineBadges
- Type: `boolean`
- Default: `true`
By default the badge text is displayed in the outline. Disable this to hide badge text from outline.
## outlineTitle
- 类型:`string`
- 默认值:`On this page`
- Type: `string`
- Default: `On this page`
可用于自定义右侧边栏的标题 (在大纲链接的顶部)。这在用另一种语言编写文档时很有用。
Can be used to customize the title of the right sidebar (on the top of outline links). This is useful when writing documentation in another language.
```js
export default {
@ -183,9 +202,9 @@ export default {
## socialLinks
- 类型:`SocialLink[]`
- Type: `SocialLink[]`
你可以定义此选项以在导航中展示带有图标的社交帐户链接。
You may define this option to show your social account links with icons in nav.
```js
export default {
@ -226,9 +245,9 @@ type SocialLinkIcon =
## footer
- 类型:`Footer`
- Type: `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 {
@ -250,9 +269,9 @@ export interface Footer {
## editLink
- 类型:`EditLink`
- Type: `EditLink`
编辑链接可让你显示链接以编辑 Git 管理服务 (例如 GitHub 或 GitLab上的页面)。有关详细信息,请参见[主题:编辑链接](../guide/theme-edit-link)。
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.
```js
export default {
@ -274,10 +293,10 @@ export interface EditLink {
## lastUpdatedText
- 类型:`string`
- 默认值:`Last updated`
- Type: `string`
- Default: `Last updated`
显示“上次更新时间”之前的前缀文本。
The prefix text showing right before the last updated time.
```ts
export default {
@ -291,11 +310,11 @@ export default {
- Type: `AlgoliaSearch`
An option to support searching your docs site using [Algolia DocSearch](https://docsearch.algolia.com/docs/what-is-docsearch). Learn more in [Theme: Search](../guide/theme-search)
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>>
locales?: Record<string, Partial<DocSearchProps>>
}
```
@ -303,9 +322,9 @@ View full options [here](https://github.com/vuejs/vitepress/blob/main/types/docs
## carbonAds
- 类型:`CarbonAdsOptions`
- Type: `CarbonAdsOptions`
显示 [Carbon Ads](https://www.carbonads.net/) 的选项。
An option to display [Carbon Ads](https://www.carbonads.net/).
```ts
export default {
@ -325,13 +344,13 @@ export interface CarbonAdsOptions {
}
```
有关详细信息,请参见 [Theme: Carbon Ads](../guide/theme-carbon-ads)
Learn more in [Default Theme: Carbon Ads](./default-theme-carbon-ads)
## docFooter
- 类型:`DocFooter`
- Type: `DocFooter`
可用于自定义出现在上一个和下一个链接上方的文本。如果不是用英语编写文档,这很有帮助。
Can be used to customize text appearing above previous and next links. Helpful if not writing docs in English.
```js
export default {
@ -370,4 +389,11 @@ Can be used to customize the sidebar menu label. This label is only displayed in
- Type: `string`
- Default: `Return to top`
Can be used to customize the label of the returnToTop. This label is only displayed in the mobile view.
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).

@ -0,0 +1,28 @@
# Edit Link
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.
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'
}
}
}
```

@ -0,0 +1,39 @@
# 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>'
}
}
}
```
Note that footer will not be displayed when the [SideBar](/reference/default-theme-sidebar) is visible.

@ -0,0 +1,154 @@
# 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
}
```
### Customizing the name color
VitePress uses the brand color (`--vp-c-brand`) 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. `guid/reference/default-theme-home-page` or `htttps://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
}
type FeatureIcon =
| string
| { src: string; alt?: string; width?: string; height: string }
| {
light: string
dark: string
alt?: string
width?: string
height: string
}
```

@ -0,0 +1,25 @@
# 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.
## Page Configuration
Add `lastUpdated` options to your config.
```js
export default {
lastUpdated: true
}
```
## Frontmatter Configuration
If you would like to hide the last update text, set false to the `lastUpdated` option.
```yaml
---
lastUpdated: false
---
```

@ -0,0 +1,38 @@
# 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](/reference/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).

@ -1,10 +1,10 @@
# 导航栏 {#nav}
# Nav
Nav 是显示在页面顶部的导航栏。 它包含站点标题、全局菜单链接等。
The Nav is the navigation bar displayed on top of the page. It contains the site title, global menu links, etc.
## 站点的标题和 logo {#site-title-and-logo}
## Site Title and Logo
默认情况下,导航的展示会引用 [`config.title`](../config/app-config#title) 配置的站点标题。如果想更改导航上显示的内容,可以在 `themeConfig.siteTitle` 选项中定义自定义文本。
By default, nav shows the title of the site referencing [`config.title`](/reference/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 {
@ -14,7 +14,7 @@ export default {
}
```
可以通过配置 `logo` 来展示站点的 logologo 应该直接放在 `public` 中,并定义为绝对路径。
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 {
@ -24,7 +24,7 @@ export default {
}
```
添加 logo 后将会与站点标题一起显示。如果只想要展示 logo 而隐藏标题,请将 `siteTitle` 设置为 `false`
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 {
@ -35,27 +35,27 @@ export default {
}
```
如果你想添加 alt 属性或根据黑暗/光明模式定制它,你也可以传递一个对象作为 logo。详情请参见 [`themeConfig.logo`](../config/theme-config#logo)。
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`](/reference/default-theme-config#logo) for details.
## 导航链接 {#navigation-links}
## Navigation Links
你可以通过定义 `themeConfig.nav` 选项来添加链接到导航。
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: 'Config', link: '/config' },
{ text: 'Changelog', link: 'https://github.com/...' }
]
}
}
```
`text` 是 nav 中显示的实际文本,`link` 是单击文本时将导航到的链接。链接的路径设置为不带 `.md` 前缀的实际文件,并始终以 `/` 开头。
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 `/`.
导航链接也可以是下拉菜单。如果要定义为下拉菜单,请在链接选项上设置 `items`
Nav links can also be dropdown menus. To do this, set `items` key on link option.
```js
export default {
@ -75,9 +75,9 @@ export default {
}
```
注意,下拉菜单标题 (上例中的 `Dropdown Menu`) 不能配置 `link` 属性,因为它变成了打开下拉对话框的按钮。
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 {
@ -114,9 +114,9 @@ export default {
}
```
### 自定义链接的“active”状态 {#customize-link-s-active-state}
### Customize link's "active" state
当页面位于匹配路径下时,导航菜单项将高亮显示。可以通过定义 `activeMatch`,值为字符串类型的正则表达式。
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 {
@ -134,8 +134,8 @@ export default {
}
```
::: warning 警告
`activeMatch` 应为正则表达式字符串,但你必须将其定义为字符串。我们不能在这里使用实际的 RegExp 对象,因为它在构建时不可序列化。
::: 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
@ -157,6 +157,6 @@ export default {
}
```
## 社交链接 {#social-links}
## Social Links
点击这里查看支持的 [`socialLinks`](../config/theme-config#sociallinks).
Refer [`socialLinks`](/reference/default-theme-config#sociallinks).

@ -1,4 +1,4 @@
# 上下页链接 {#prev-next-link}
# 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.
@ -40,4 +40,4 @@ You can customize the text and link for the previous and next pages (shown at do
## next
Same as `prev` but for the next page.
Same as `prev` but for the next page.

@ -1,9 +1,10 @@
# 搜索 {#search}
# Search
VitePress 支持使用 [Algolia DocSearch](https://docsearch.algolia.com/docs/what-is-docsearch) 来让你的站点具有搜索功能。可以参考它们的入门指南。在你的 `.vitepress/config.ts` 中,你至少需要做如下的配置才能让它起作用:
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: {
algolia: {
@ -15,18 +16,20 @@ export default defineConfig({
})
```
如果你认为 DocSearch 不合适,你可以使用社区的插件,像 <https://github.com/emersonbottero/vitepress-plugin-search> 或者在 [这个 GitHub 议题](https://github.com/vuejs/vitepress/issues/670)下寻找一些自定义的解决方案。
If you are not eligible for DocSearch, you might wanna use some community plugins like <https://github.com/emersonbottero/vitepress-plugin-search> or explore some custom solutions on [this GitHub thread](https://github.com/vuejs/vitepress/issues/670).
## 国际化 {#i8n}
## i18n
你可以这样配置来使站点支持多种语言的搜索功能:
You can use a config like this to use multilingual search:
```ts
import { defineConfig } from 'vitepress'
export default defineConfig({
// ...
themeConfig: {
// ...
algolia: {
appId: '...',
apiKey: '...',
@ -79,4 +82,4 @@ export default defineConfig({
})
```
[这些参数](https://github.com/vuejs/vitepress/blob/main/types/docsearch.d.ts)可以被覆盖,参考 Algolia 官方文档了解更多信息。
[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.

@ -0,0 +1,182 @@
# Sidebar
The sidebar is the main navigation block for your documentation. You can configure the sidebar menu in [`themeConfig.sidebar`](/reference/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: [...]
}
]
}
}
```

@ -23,13 +23,13 @@ const members = [
]
</script>
# Team 页面 {#team-page}
# 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}
## Show team members in a page
你可以使用从 `vitepress/theme` 提供的 `<VPTeamMembers>` 组件在任何页面上显示团队成员列表。
You may use `<VPTeamMembers>` component exposed from `vitepress/theme` to display a list of team members on any page.
```html
<script setup>
@ -56,21 +56,21 @@ Say hello to our awesome team.
<VPTeamMembers size="small" :members="members" />
```
以上将在卡片外观元素中显示团队成员。它应该显示成下面的内容。
The above will display a team member in card looking element. It should display something similar to below.
<VPTeamMembers size="small" :members="members" />
`<VPTeamMembers>` 组件有 2 种不同的大小,`small` 和 `medium`。虽然归结为你的偏好,但通常“小”尺寸在文档页面中使用时应该更适合。此外,你可以为每个成员添加更多属性,例如添加“描述”或“赞助商”按钮。在 [`<VPTeamMembers>`](#vpteammembers) 中了解更多信息。
`<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).
在 doc 页面中的嵌入团队成员对小型团队非常有用,在这些团队中,拥有专用的完整团队页面可能太多,或者介绍部分成员作为文档上下文的参考也是有用的。
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.
如果你有大量成员,或者只是想有更多空间来展示团队成员,可以考虑[创建一个完整的团队页面](#create-a-full-team-page)。
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}
## Create a full Team Page
除了将团队成员添加到文档页面之外,你还可以创建一个完整的团队页面,类似于创建自定义[主页](./theme-home-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](/reference/default-theme-home-page).
要创建团队页面,首先,创建一个新的 md 文件。文件名不重要不过这里我们命名为“team.md”。在这个文件中设置 frontmatter 选项`layout: page`,然后你可以使用`TeamPage`组件来组成你的页面结构。
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
---
@ -113,17 +113,17 @@ const members = [
</VPTeamPage>
```
创建完整的团队页面时,请记住使用 `<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>` 组件添加页面标题部分。标题是 `<h1>` 标题。 使用 `#title``#lead` 插槽来记录你的团队。
`<VPPageTitle>` component adds the page title section. The title being `<h1>` heading. Use `#title` and `#lead` slot to document about your team.
`<VPMembers>` 的工作方式与在文档页面中使用时相同。 它将显示成员列表。
`<VPMembers>` works as same as when used in a doc page. It will display list of members.
### 添加 “sections” 来区分不同的团队成员 {#add-sections-to-divide-team-members}
### Add sections to divide team members
你可以将 “sections” 添加到团队页面。例如,你可能有不同类型的团队成员,例如核心团队成员和社区合作伙伴。你可以将这些成员划分为多个部分,以更好地解释每个组的角色。
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.
为此,请将 `<VPTeamPageSection>` 组件添加到我们之前创建的 `team.md` 文件中。
To do so, add `<VPTeamPageSection>` component to the `team.md` file we created previously.
```html
---
@ -157,13 +157,13 @@ const partners = [...]
</VPTeamPage>
```
`<VPTeamPageSection>` 组件可以具有类似于 `VPTeamPageTitle` 组件的 `#title``#lead` 插槽,以及用于显示团队成员的 `#members` 插槽。
The `<VPTeamPageSection>` component can have `#title` and `#lead` slot similar to `VPTeamPageTitle` component, and also `#members` slot for displaying team members.
请记住将 `<VPTeamMembers>` 组件放入 `#members` 插槽中。
Remember to put in `<VPTeamMembers>` component within `#members` slot.
## `<VPTeamMembers>`
`<VPTeamMembers>` 组件显示传入的成员列表。
The `<VPTeamMembers>` component displays a given list of members.
```html
<VPTeamMembers
@ -207,7 +207,7 @@ interface TeamMember {
// Social links. e.g. GitHub, Twitter, etc. You may pass in
// the Social Links object here.
// See: https://vitepress.vuejs.org/config/theme-config.html#sociallinks
// See: https://vitepress.vuejs.org/reference/default-theme-config.html#sociallinks
links?: SocialLink[]
// URL for the sponsor page for the member.
@ -217,11 +217,11 @@ interface TeamMember {
## `<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>`
添加页面的“标题”部分。 最好在 `<VPTeamPage>` 的开头使用。 它接受 `#title``#lead` 插槽。
Adds "title" section of the page. Best use at the very beginning under `<VPTeamPage>`. It accepts `#title` and `#lead` slot.
```html
<VPTeamPage>
@ -239,7 +239,7 @@ interface TeamMember {
## `<VPTeamPageSection>`
在团队页面中创建一个“部分”。它接受`#title`、`#lead` 和 `#members` 插槽。你可以在 `<VPTeamPage>` 中添加任意数量的“部分”。
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>

@ -0,0 +1,145 @@
---
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](/reference/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](/reference/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](/reference/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 <Badge type="info" text="default theme only" />
- 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="default theme only" /> <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](/reference/default-theme-home-page).
### features <Badge type="info" text="default theme only" /> <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](/reference/default-theme-home-page).
### aside <Badge type="info" text="default theme only" />
- Type: `boolean`
- Default: `true`
If you want the right aside component in `doc` layout not to be shown, set this option to `false`.
```yaml
---
aside: false
---
```
### outline <Badge type="info" text="default theme only" />
- 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](/reference/default-theme-config#outline), and it overrides the theme config.
### lastUpdated <Badge type="info" text="default theme only" />
- Type: `boolean`
- Default: `true`
Whether to display [Last Updated](/reference/default-theme-last-updated) text in the current page.
```yaml
---
lastUpdated: false
---
```

@ -0,0 +1,143 @@
# 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>
}
interface PageData {
title: string
titleTemplate?: string | boolean
description: string
relativePath: 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 {
route: Route
go: (href?: string) => Promise<void>
}
```
## `withBase` <Badge type="info" text="helper" />
- **Type**: `(path: string) => string`
Appends the configured [`base`](/reference/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>
```
## `$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,525 @@
---
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.
<div class="site-config-toc">
[[toc]]
</div>
<style>
@media (min-width: 1280px) {
.site-config-toc {
display: none;
}
}
</style>
## 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`, `.cjs`, `.mjs`, `.cts`, 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.',
...
}
```
### 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`
}
})
```
## 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
export default {
head: [
[
'link',
{ rel: 'preconnect', href: 'https://fonts.gstatic.com', crossorigin: '' }
]
// would render: <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
]
}
```
```ts
type HeadConfig =
| [string, Record<string, string>]
| [string, Record<string, string>, string]
```
### 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 <-> 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'
}
```
### 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'`
- 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
}
```
### mpa <Badge type="warning" text="experimental" />
- Type: `boolean`
- Default: `false`
When set to `true`, the production app will be built in [MAP 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'`
- 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.
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.
### 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`](/reference/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://shiki.matsu.io/) to highlight language syntax. Inside this option, you may pass various Markdown related options to fit your needs.
```js
export default {
markdown: {
theme: 'material-theme-palenight',
lineNumbers: true
}
}
```
Below are all the options that you can have in this object:
```ts
interface MarkdownOptions extends MarkdownIt.Options {
// Custom theme for syntax highlighting.
// You can use an existing theme.
// See: https://github.com/shikijs/shiki/blob/main/docs/themes.md#all-themes
// Or add your own theme.
// See: https://github.com/shikijs/shiki/blob/main/docs/themes.md#loading-theme
theme?:
| Shiki.IThemeRegistration
| { light: Shiki.IThemeRegistration; dark: Shiki.IThemeRegistration }
// Enable line numbers in code block.
lineNumbers?: boolean
// Add support for your own languages.
// https://github.com/shikijs/shiki/blob/main/docs/languages.md#supporting-your-own-languages-with-shiki
languages?: Shiki.ILanguageRegistration
// markdown-it-anchor plugin options.
// See: https://github.com/valeriangalliat/markdown-it-anchor#usage
anchor?: anchorPlugin.AnchorOptions
// markdown-it-attrs plugin options.
// See: https://github.com/arve0/markdown-it-attrs
attrs?: {
leftDelimiter?: string
rightDelimiter?: string
allowedAttributes?: string[]
disable?: boolean
}
// specify default language for syntax highlighter
defaultHighlightLang?: string
// @mdit-vue/plugin-frontmatter plugin options.
// See: https://github.com/mdit-vue/mdit-vue/tree/main/packages/plugin-frontmatter#options
frontmatter?: FrontmatterPluginOptions
// @mdit-vue/plugin-headers plugin options.
// See: https://github.com/mdit-vue/mdit-vue/tree/main/packages/plugin-headers#options
headers?: HeadersPluginOptions
// @mdit-vue/plugin-sfc plugin options.
// See: https://github.com/mdit-vue/mdit-vue/tree/main/packages/plugin-sfc#options
sfc?: SfcPluginOptions
// @mdit-vue/plugin-toc plugin options.
// See: https://github.com/mdit-vue/mdit-vue/tree/main/packages/plugin-toc#options
toc?: TocPluginOptions
// Configure the Markdown-it instance.
config?: (md: MarkdownIt) => void
}
```
### vite
- Type: `import('vite').UserConfig`
Pass raw [Vite Config](https://vitejs.dev/config/) to internal Vite dev server / bundler.
### 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.
## 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 `ctx`.
:::
```ts
export default {
async transformHead(context) {
// ...
}
}
```
```ts
interface TransformContext {
siteConfig: SiteConfig
siteData: SiteData
pageData: PageData
title: string
description: string
head: HeadConfig[]
content: string
}
```
### transformHtml
- Type: `(code: string, id: string, ctx: 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 `ctx`. Also, modifying the html content may cause hydration problems in runtime.
:::
```ts
export default {
async transformHtml(code, id, context) {
// ...
}
}
```
### transformPageData
- Type: `(pageData: PageData) => 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 PageData.
```ts
export default {
async transformPageData(pageData) {
pageData.contributors = await getPageContributors(pageData.relativePath)
}
// or return data to be merged
async transformPageData(pageData) {
return {
contributors: await getPageContributors(pageData.relativePath)
}
}
}
```
Loading…
Cancel
Save