VitePress 学习(全面拥抱vite)---翻译

11,067 阅读10分钟

什么是VitePress?

VitePress 是早期的 WIP!目前的重点是首先使 Vite 稳定和功能完整。目前还不建议在任何重要的情况下使用这个

VitePress 是 VuePress 的兄弟,它建立在 Vite 之上

vuePress=webpack+vue2,vitePress=vite+vue3

动机

我们喜欢 VuePress v1,但是由于构建在 Webpack 之上,对于一个只有几个页面的简单文档站点来说,启动开发服务器所花费的时间简直令人难以忍受。而且 HMR 更新也可能需要数秒才能反映到浏览器中

作为参考,Composition API RFC repo 只有两个页面,但是启动服务器需要 4 秒,而在浏览器中反映任何编辑几乎需要 2 秒。

从根本上说,这是因为 VuePress v1 在本质上是一个 Webpack 应用程序。即使只有两个页面,它也是一个完整的正在编译的 Webpack 项目(包括所有主题源文件)。更糟糕的是,当项目有很多页面时,服务器必须首先完全编译每个页面,然后才能显示任何内容

顺便说一句,Vite 很好地解决了这些问题:服务器几乎立即启动,按需编译只编译所服务的页面,以及快速的 HMR。另外,随着时间的推移,我注意到 VuePress v1 中还有一些额外的设计问题,但由于需要大量的重构,一直没有时间来修复。

现在,有了 Vite 和 Vue 3,真的是时候重新考虑“Vue 驱动的静态站点生成器”

在 VuePress v1 的改进

VuePress v1....有一些改进

它使用的是 Vue 3

利用 Vue 3 改进的模板静态分析来尽可能严格地约束静态内容。静态内容以字符串文本的形式发送,而不是 JavaScript 呈现函数代码,因此 JS 有效负载解析起来更容易,hydration也变得更快。

客户端接到 SSR 响应之后,为了支持(基于 JavaScript 的)交互功能,仍然需要创建出组件树,与 SSR 渲染的 HTML 关联起来,并绑定相关的 DOM 事件,让页面变得可交互,这个过程称为 hydration

注意:应用优化的同时仍然允许用户在 markdown 内容中自由混合 Vue 组件–编译器会自动为您进行静态/动态分离,您无需考虑它。

它使用 Vite 之下的优势

  • 更快的开发服务器启动

  • 更快的热更新

  • 更快的构建(内部使用 Rollup)

更轻的页面

  • Vue 3 摇树 + Rollup 代码拆分(摇掉代码中未引用部分(dead-code),production 模式下会自动使用 tree-shaking 打包时除去未引用的代码。作用是优化项目代码)

  • 不为每个请求的每个页面提供元数据。这样可以将页面权重从总页面数中分离出来。只发送当前页的元数据。客户端导航同时获取新页面的组件和元数据

  • 不使用 vue-router,因为 VitePress 的需求非常简单和具体-使用一个简单的自定义路由器(低于 200 LOC)代替。

  • (WIP) i18n 区域设置数据也应该按需获取。

其他不同

VitePress 更多的是坚持自己想法和减少配置:VitePress 的目标是缩小当前 VuePress 的复杂性,并从它的最简主义根源重新开始。

VitePress 是面向未来的:VitePress 只针对支持原生 ES 模块导入的浏览器。它鼓励使用不需要翻译的本地 JavaScript 和用于主题化的 CSS 变量。

这会成为未来的下一个 VuePress 吗?

我们已经有了 VuePress -next,这将是 VuePress 的下一个主要版本。它还比 VuePress v1 做了很多改进,现在还支持 Vite。VitePress 不兼容当前的 VuePress 生态系统(主要是主题和插件)。总体想法是,VitePress 将拥有一个更简约的主题 API(更喜欢 JavaScript API 而不是文件布局约定),并且可能没有插件(所有定制都在主题中完成)。

入门

本节将帮助您从头开始构建一个基本的 VitePress 文档站点。如果您已经有了一个现有的项目,并且希望将文档保存在项目中,那么从步骤 3 开始。

步骤 1:创建并更改到一个新目录。

mkdir vitepress-starter && cd vitepress-starter

步骤 2:用首选yarn包管理器初始化。

yarn init

步骤 3:本地安装 VitePress

yarn add --dev vitepress

步骤 4:创建您的第一个文档

mkdir docs && echo '# Hello VitePress' > docs/index.md

步骤 5:向 package.json 中添加一些脚本。

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

步骤 6:在本地服务器上提供文档站点。

$ yarn run docs:dev

到目前为止,您应该已经有了一个基本但功能强大的 VitePress 文档站点。

当您的文档站点开始形成时,请务必阅读部署指南

结构

没有任何配置,页面非常小,用户无法在站点周围导航。为了定制你的站点,让我们首先在 docs 目录中创建一个。vitepress 目录。

这是所有特定于 vitepress 的文件将被放置的地方。您的项目结构可能是这样的

.
├─ docs
│  ├─ .vitepress
│  │  └─ config.js
│  └─ index.md
└─ package.json

image.png

配置 VitePress 站点的基本文件是.VitePress/config.js,它应该导出一个 JavaScript 对象:

module.exports = {
  title: 'Hello VitePress',
  description: 'Just playing around.'
}

image.png

查看配置参考以获得完整的选项列表

资源处理

相对路径

所有的 Markdown 文件都会被 webpack 编译成 Vue 组件,因此你可以,并且应该更倾向于使用相对路径(Relative URLs)来引用所有的静态资源:

文件需要放到docs下,不然图片显示不出来

![An image](./image.png)

image.png

你可以在你的 markdown 文件中引用静态资产。使用绝对公共路径(基于项目根目录)或相对路径(基于您的文件系统)的主题、样式和普通的.css 文件中的 Vue 组件。如果您使用过 vue-cli 或 webpack 的文件加载器file-load,后者类似于您所习惯的行为。

常见的图像、媒体和字体文件类型将被自动检测并作为资产包括进来。

所有引用的资源,包括那些使用绝对路径的资源,都将被复制到生产版本中带有哈希文件名的 dist 文件夹中。从未引用过的资产将不会被复制。与 vue-cli 类似,小于 4kb 的图像资产将采用 base64 内联。

公共文件

有时你可能需要提供静态资产,这些资产不会直接被你的 Markdown 或主题组件引用(例如,favicons 和 PWA icons)。项目根目录下的公共目录可以用作一个逃生出口,以提供静态资产,这些资产要么永远不会在源代码中引用(例如 robots.txt),要么必须保持完全相同的文件名(没有散列)。

放置在公共位置的资产将原样复制到 dist 目录的根目录中。

请注意,应该使用根绝对路径引用公共文件-例如,public/icon.png 在源代码中应始终作为/icon.png 引用。

基础路径

如果站点部署到非根 URL,则需要在.vitepress/config.js 中设置 base 选项。例如,如果您计划将站点部署到foo.github.io/bar/,则应将bas…

对于基本 URL,要在公共场合引用图像,必须使用/bar/image.png 这样的 URL。但如果你决定改变基础,这是脆弱的。为了帮助实现这一点,VitePress 提供了一个内置的助手$withBase(注入到 Vue 的原型中),它可以生成正确的路径:

<img :src="$withBase('/foo.png')" alt="foo" />

image.png

Markdown 拓展

Header Anchors

所有的标题将会自动地应用 anchor 链接,anchor 的渲染可以通过 markdown.anchor 来配置。

链接

内部连接

内部链接转换为路由器链接,用于 SPA 导航。此外,每个子目录中包含的每个 index.md 都将自动转换为 index.html,并带有相应的 URL/。

例如,给定以下目录结构:

.
├─ index.md
├─ foo
│  ├─ index.md
│  ├─ one.md
│  └─ two.md
└─ bar
   ├─ index.md
   ├─ three.md
   └─ four.md

提供其中之一 foo/one.md

[Home](/) <!-- 跳转到根部的 README.md -->
[foo](/foo/) <!-- 跳转到 foo 文件夹的 index.html -->
[foo heading](./#heading) <!-- 跳转到 foo/index.html 的特定标题位置 -->
[bar - three](../bar/three.md) <!-- 具体文件可以使用 .md 结尾(推荐) -->
[bar - four](../bar/four.html) <!-- 也可以用 .html -->

image.png

image.png

image.png

页面后缀

默认情况下,生成的页面和内部链接的后缀是.html。

外部链接

出站的链接自动获得target=" blank" rel="noopener noreferrer

前言

YAML frontmatter 外网 支持开箱即用:

注意的是采用三虚线必须放置在 markdown 文件的 最上面

---
title: Blogging Like a Hacker
lang: en-US
---

frontmatter

可供选择的 frontmatter 格式

任何包含 YAML frontmatter 块的 Markdown 文件都将被 gray matter 处理。frontmatter 必须位于 Markdown 文件的顶部,并且必须采用三条虚线之间的有效 YAML 集的形式。例子:

$frontmatter 很重要,vitePress 只识别这个----三条虚线块有且只有一个

---
title: tags
date: 2019-08-13 09:39:50
type: tags
layout: tag
---


# Hello VitePress


# {{ $frontmatter.date }}

在三虚线之间,您可以设置预定义的变量,甚至创建您自己的自定义变量。这些变量可以通过$frontmatter 变量来使用。这里有一个例子,你可以在你的 Markdown 文件中使用它

VitePress 还支持 JSON 前端语法,以花括号开始和结束【俩种写法不能共存】

---
{
  "title": "Blogging Like a Hacker",
  "editLink": true
}
---

# {{ $frontmatter.title }}
预定义的变量

vitepress.vuejs.org/guide/front…

  • title (default h1_title || siteData.title): 当前页面的标题

image.png

image.png

  • head (default undefined): 指定要注入的额外头标记:
---
head:
  - - meta
    - name: description
      content: hello
  - - meta
    - name: keywords
      content: super duper SEO
---

image.png

  • navbar(default undefined): 你可以用导航栏:false 来禁用特定页面上的导航栏

头部消失 image.png

  • sidebar(default undefined): 你可以决定在一个特定的页面上用 sidebar: auto 显示 sidebar,或者用 sidebar: false 禁用它

左边消失 image.png

  • editLink(default undefined): 定义此页是否应该包含编辑链接

  • date: 这里的日期会覆盖帖子名称中的日期。这可以用来确保正确排序的职位。日期的格式为 YYYY-MM-DD HH:MM:SS+/-TTTT;小时、分钟、秒和时区偏移是可选的。

  • tags: 类似于类别,一个或多个标签可以添加到一个帖子。与类别一样,标记也可以指定为 YAML 列表或空格分隔的字符串。

该数据对页面的其余部分以及所有自定义和主题化组件都可用。

详情请参阅 Frontmatter

GitHub 风格的表格

| Tables        | Are           | Cool  |
| ------------- |:-------------:| -----:|
| col 3 is      | right-aligned | $1600 |
| col 2 is      | centered      |   $12 |
| zebra stripes | are neat      |    $1 |

输出

TablesAreCool
col 3 isright-aligned$1600
col 2 iscentered$12
zebra stripesare neat$1
  • 表情
:tada: :100:

输出

image.png

  • 内容目录
[[toc]]

输出

image.png

目录(Table of Contents)的渲染可以通过 markdown.toc 选项来配置。

自定义容器

自定义容器可以通过它们的类型、标题和内容来定义

默认提示

::: tip
This is a tip
:::

::: warning
This is a warning
:::

::: danger
This is a dangerous warning
:::

输出

image.png

自定义提示

::: danger STOPxxxxxx
Danger zone, do not proceed
:::

输出

image.png

代码块中的语法高亮显示

```js
export default {
  name: 'MyComponent',
  // ...
}
```

输出

export default {
  name: 'MyComponent'
  // ...
}
```html
<ul>
  <li v-for="todo in todos" :key="todo.id">
    {{ todo.text }}
  </li>
</ul>
```

输出

<ul>
  <li v-for="todo in todos" :key="todo.id">{{ todo.text }}</li>
</ul>

Prism 网站上有有效语言的列表。

image.png

image.png

image.png

image.png

代码块中的行高亮显示

```js{4}
export default {
  data () {
    return {
      msg: 'Highlighted!'
    }
  }
}
```

输出

image.png

除了单行之外,您还可以指定多个单行、范围或同时指定

  • 行范围:例如{5-8},{3-10},{10-17}
  • 多个单行:例如{4,7,9}
  • 行范围和单行:例如{4,7-13,16,23-27,40}
```js{1,4,6-7}
export default { // Highlighted
  data () {
    return {
      msg: `Highlighted!
      This line isn't highlighted,
      but this and the next 2 are.`,
      motd: 'VitePress is awesome',
      lorem: 'ipsum',
    }
  }
}

输出

image.png

行号

您可以通过 config 为每个代码块启用行号

module.exports = {
  markdown: {
    lineNumbers: true
  }
}

导入代码片段

您可以通过以下语法从现有文件导入代码片段

<<< @/filepath

image.png

image.png

它还支持行高亮显示

<<< @/filepath{highlightLines}

image.png

image.png

此处的 @ 默认值是 process.cwd()。

你也可以使用 VS Code 区域只包含代码文件的相应部分。您可以在文件路径后面的#后面提供自定义区域名称(默认情况下是代码片段)

进阶配置

VitePress 使用 markdown-it 来渲染 Markdown,上述大多数的拓展也都是通过自定义的插件实现的。想要进一步的话,你可以通过 .vitepress/config.js 的 markdown 选项,来对当前的 markdown-it 实例做一些自定义的配置:

module.exports = {
  markdown: {
    // markdown-it-anchor 的选项
    anchor: { permalink: false },

    // markdown-it-toc 的选项
    toc: { includeLevel: [1, 2] },

    config: (md) => {
      // 使用更多的 markdown-it 插件!
      md.use(require('markdown-it-xxx'))
    }
  }
}

在 Markdown 中使用 Vue

浏览器的 API 访问限制

当你在开发一个 VitePress 应用时,由于所有的页面在生成静态 HTML 时都需要通过 Node.js 服务端渲染,因此所有的 Vue 相关代码都应当遵循 编写通用代码 的要求。简而言之,请确保只在 beforeMount 或者 mounted 访问浏览器 / DOM 的 API。

如果您正在使用或演示的组件不是 ssr 友好的(例如,包含自定义指令),您可以将它们包装在内置的组件中

<ClientOnly>
  <NonSSRFriendlyComponent/>
</ClientOnly>

请注意,这并不能解决一些组件或库在导入时就试图访问浏览器 API 的问题 —— 如果需要使用这样的组件或库,你需要在合适的生命周期钩子中动态导入它们

<script>
export default {
  mounted () {
    import('./lib-that-access-window-on-import').then(module => {
      // use code
    })
  }
}
</script>

如果你的模块导出了一个默认的 Vue 组件,你可以动态注册它

<template>
  <component v-if="dynamicComponent" :is="dynamicComponent"></component>
</template>

<script>
export default {
  data() {
    return {
      dynamicComponent: null
    }
  },

  mounted () {
    import('./lib-that-access-window-on-import').then(module => {
      this.dynamicComponent = module.default
    })
  }
}
</script>

v3.cn.vuejs.org/guide/compo…

模板语法

插值

每一个 Markdown 文件将首先被编译成 HTML,接着作为一个 Vue 组件传入 vue-loader,这意味着你可以在文本中使用 Vue 风格的插值:

{{ 1 + 1 }}

输出

2
指令

同样地,也可以使用指令:

<span v-for="i in 3">{{ i }} </span>

输出

123
访问网站以及页面的数据
{{ $page }}

输出

{
    "title": "tagsadsandbsamnbdmnasbdnmasbd",
    "description": "hello",
    "frontmatter": {
        "title": "tagsadsandbsamnbdmnasbdnmasbd",
        "editLink": true,
        "tags": "dd",
        "head": [
            [
            "meta",
                {
                "name": "description",
                "content": "hello"
                }
            ],
            [
            "meta",
                {
                 "name": "keywords",
                 "content": "super duper SEO"
                 }
            ]
                ]
            },
        "relativePath": "index.md",
        "lastUpdated": 1621777101000
    }

Escaping

默认情况下,块级 (block) 的代码块将会被自动包裹在 v-pre 中。如果你想要在内联 (inline) 的代码块或者普通文本中显示原始的大括号,或者一些 Vue 特定的语法,你需要使用自定义容器 v-pre 来包裹:

::: v-pre
`{{ This will be displayed as-is }}`
:::

输出

image.png

使用组件

当你需要更多的灵活性时,VitePress 允许你用自己的 Vue 组件扩展你的创作工具箱。

低价导入组件

如果您的组件将只在少数地方使用,那么推荐的使用方法是在使用它的文件中导入组件。

# Docs

This is a .md using a custom component

<CustomComponent />

## More docs

...

<script setup>
import CustomComponent from '../components/CustomComponent.vue'
</script>
在主题中注册全局组件

如果这些组件将在文档中的多个页面中使用,它们可以在主题中全局注册(或者作为扩展默认 VitePress 主题的一部分)。查看定制指南获取更多信息。

在.vitepress/theme/index.js 中,enhanceApp 函数接收 Vue 应用程序实例,以便您可以像在常规 Vue 应用程序中一样注册组件。

import DefaultTheme from 'vitepress/theme'

export default {
  ...DefaultTheme,
  enhanceApp({ app }) {
    app.component('VueClickAwayExample', VueClickAwayExample)
  }
}

稍后在您的标记文件中,组件可以在内容之间交错

# Vue Click Away

<VueClickAwayExample />

重要:请确保一个自定义组件的名字包含连接符或者是 PascalCase,否则,它将会被视为一个内联元素,并被包裹在一个

标签中,这将会导致 HTML 渲染紊乱,因为 HTML 标准规定,

标签中不允许放置任何块级元素。

在标题中使用组件
Markdown输出的 HTML解析后的标题
# text <Tag/> <h1>text <Tag/></h1>text
# text <h1>text <code>&lt;Tag/&gt;</code></h1>text <Tag/>
由<code>封装的 HTML 将按原样显示;只有没有包装的 HTML 才会被 Vue 解析。

输出的 HTML 由 markdown-it 完成。而解析后的标题由 VuePress 完成,用于侧边栏以及文档的标题。

使用预处理器

VitePress 内置了对 CSS 预处理器的支持:.scss, .sass, .less, . style 和.stylus 文件。不需要为它们安装特定于 vite 的插件,但是必须安装相应的预处理器本身

# .scss and .sass
npm install -D sass

# .less
npm install -D less

# .styl and .stylus
npm install -D stylus

然后您可以在 Markdown 和主题组件中使用以下内容

<style lang="sass">
.title
  font-size: 20px
</style>

脚本和样式提升

有时,你可以只想在当前页面应用一些 JavaScript 或者 CSS,在这种情况下,你可以直接在 Markdown 文件中使用原生的 <script> 或者 <style> 标签,它们将会从编译后的 HTML 文件中提取出来,并作为生成的 Vue 单文件组件的 <script><style> 标签

内置组件

VitePress 提供内置的 Vue 组件,如 ClientOnly 和 OutboundLink,查看全局组件指南了解更多信息

部署

下述的指南基于以下条件:

  1. 文档放置在项目的 docs 目录中;
  2. 使用的是默认的构建输出位置 (.vitepress/dist);
  3. VitePress 以本地依赖的形式被安装到你的项目中,并且配置了如下的 npm scripts:
{
  "scripts": {
    "docs:build": "vitepress build docs",
    "docs:serve": "vitepress serve docs"
  }
}

构建文档

你可以运行 yarn docs:build 命令来构建这些文档。

 yarn docs:build

默认情况下,生成输出将放置在.vitepress/dist。您可以将此 dist 文件夹部署到任何首选平台。

本地测试文档

一旦你构建了这些文档,你可以通过运行 yarn docs:serve 命令在本地测试它们。

 yarn docs:build
 yarn docs:serve

serve 命令将启动本地静态 web 服务器,该服务器在以下位置为.vitepress/dist 中的文件提供服务:http://localhost:5000。这是一种简单的方法,可以检查生产构建在您的本地环境中是否正常。

您可以配置服务器的端口 py 传递——port 标志作为一个参数。

{
  "scripts": {
    "docs:serve": "vitepress serve docs --port 8080"
  }
}

现在 docs:serve method 将在启动服务器 http://localhost:8080.

GitHub Pages

  1. docs/.vitepress/config.js 中设置正确的base

如果要部署到 https://<USERNAME>.github.io/,则可以省略 base,因为它默认为“/”。

如果您正在部署到 https://<USERNAME>.github.io/<REPO>/,例如,您的存储库位于github.com//,然后将 base 设置为“//”。

  1. 在你的项目中,创建一个如下的 deploy.sh 文件(请自行判断去掉高亮行的注释):
#!/usr/bin/env sh

# 确保脚本抛出遇到的错误
set -e

# 生成静态文件
npm run docs:build

# 进入生成的文件夹
cd docs/.vuepress/dist

# 如果是发布到自定义域名
# echo 'www.example.com' > CNAME

git init
git add -A
git commit -m 'deploy'

# 如果发布到 https://<USERNAME>.github.io
# git push -f git@github.com:<USERNAME>/<USERNAME>.github.io.git master

# 如果发布到 https://<USERNAME>.github.io/<REPO>
# git push -f git@github.com:<USERNAME>/<REPO>.git master:gh-pages

cd -

你可以在你的持续集成的设置中,设置在每次 push 代码时自动运行上述脚本。

GitHub Pages and Travis CI
  1. docs/.vitepress/config.js 中设置正确的base

如果要部署到 https://.gitlab.io/,则可以省略 base,因为它默认为“/”。

如果您正在部署到 https://.gitlab.io//,例如,您的存储库位于gitlab.com//,然后将 base 设置为“//”。

  1. dest in .vitepress/config.js 设置为 public.

  2. 在项目的根目录中创建一个名为.gitlab-ci.yml 的文件,其内容如下。这将在您对内容进行更改时构建和部署您的站点

image: node:10.22.0
pages:
  cache:
    paths:
      - node_modules/
  script:
    - yarn install # npm install
    - yarn docs:build # npm run docs:build
  artifacts:
    paths:
      - public
  only:
    - master

Netlify

  1. Netlify上,使用以下设置从 GitHub 设置新项目:
  • Build 命令:vitepress Build docsyarn docs:build or npm run docs:build
  • 发布目录:docs/.vitepress/dist
  1. 点击部署按钮。

Google Firebase

  1. 确保已安装 firebase 工具。

  2. 在项目根目录下创建 firebase.json.firebaserc,内容如下:

firebase.json 文件:

{
  "hosting": {
    "public": "./docs/.vitepress/dist",
    "ignore": []
  }
}

.firebaserc

{
 "projects": {
   "default": "<YOUR_FIREBASE_ID>"
 }
}

运行 yarn docs:buildnpm run docs:build 后,使用 firebase deploy 命令部署。

Surge

  1. 如果你还没有安装的话,请先安装 surge

  2. 运行 yarn docs:build or npm run docs:build.

  3. 通过键入 surge docs/.vitepress/dist 部署到 surge。

您还可以通过添加 surge docs/.vitepress/dist yourdomain.com 来部署到自定义域。

Heroku

  1. 安装 Heroku CLI.

  2. 通过注册创建一个 Heroku 帐户

  3. 运行 heroku 登录并填写你的 Heroku 证书:

heroku login

在你的项目根目录中,创建一个名为 static.json 的文件,并包含下述内容:

static.json

{
  "root": "./docs/.vitepress/dist"
}

这是你网站的配置;更多信息请阅读 heroku-buildpack-static

  1. 设置你的 Heroku git 远程
# version change
$ git init
$ git add .
$ git commit -m "My site ready for deployment."

# creates a new app with a specified name
$ heroku apps:create example

# set buildpack for static sites
$ heroku buildpacks:set https://github.com/heroku/heroku-buildpack-static.git
  1. 部署您的站点
# publish site
$ git push heroku master

# opens a browser to view the Dashboard version of Heroku CI
$ heroku open

Vercel

要使用Vercel for Git部署 VitePress 应用程序,请确保已将其推送到 Git 存储库。

vercel.com/import/git 并使用您选择的 Git(GitHub、GitLab 或 BitBucket)将项目导入 Vercel。按照向导使用项目的 package.json 选择项目根目录,并使用 yarn docs:build or npm run docs:build 并且 输出目录为./docs/.vitepress/dist

image

导入项目之后,所有后续推送到分支的操作将生成 Preview Deployment,对生产分支(通常是“主分支”)所做的所有更改将导致生产部署。

部署后,您将获得一个 URL 以实时查看您的应用程序,例如:vitepress.vercel.app

深入

全局计算属性

在 VitePress 中,一些核心计算属性可以被默认主题或自定义主题使用。或者直接在 Markdown 页面使用 vue,例如使用$frontmatter.title访问在页面的前部部分定义的标题。

$site

这是你现在看到的这个网站的 $site 的值

{
    "lang": "en-US",
    "title": "Hello VitePress默认x",
    "description": "Just playing around.摸鱼", "base": "/",
    "head": [],
    "themeConfig": {},
    "locales": {},
    "customData": {}
    }

$themeConfig

指向$site.themeConfig

{
  locales: {},
  repo: 'vuejs/vitepress',
  docsDir: 'docs',
  editLinks: true,
  editLinkText: 'Edit this page on GitHub',
  lastUpdated: 'Last Updated',
  nav: [...],
  sidebar: { ... }
}

$page

这是你现在看到的这个页面的 $page 的值:

{
  relativePath: 'guide/global-computed.md',
  title: 'Global Computed',
  headers: [
    { level: 2, title: '$site', slug: 'site' },
    { level: 2, title: '$page', slug: '$page' },
    ...
  ],
  frontmatter: $frontmatter,
  lastUpdated: 1606297645000
}

$frontmatter

指向的是$page.frontmatter

{
  title: 'Docs with VitePress',
  editLink: true
}

$lang

当前页面的语言,默认值为 en-US。

$localePath

当前页面的 locale 路径前缀,默认值为 /

$title

用于当前页面的 <title> 标签的值。

$description

用于当前页面的 <meta name="description" content="..."> 的 content 值。

$withBase

Helper 方法通过在.vitepress/config.js 中配置的基本路径前面加上前缀来生成正确的路径。当您想链接到具有基本路径的公共文件时,它很有用。

全局组件

VitePress 只有很少的内置组件可以在全球范围内使用。您可以在您的标记或自定义主题配置中使用这些组件。

Content

Content 组件显示呈现的标记内容。在创建自己的主题时很有用

指定一个指定页面的特定 slot 用于渲染---应该跟 vuePress 类似[文档不怎么具体]

<template>
  <h1>Custom Layout!</h1>
  <Content />
</template>

ClientOnly

vuepress一致

ClientOnly 组件仅在客户端渲染其插槽。

当你在开发一个 VitePress 应用时,由于所有的页面在生成静态 HTML 时都需要通过 Node.js 服务端渲染,因此所有的 Vue 相关代码都应当遵循 编写通用代码 的要求。简而言之,请确保只在 beforeMount 或者 mounted 访问浏览器 / DOM 的 API。

如果你正在使用,或者需要展示一个对于 SSR 不怎么友好的组件(比如包含了自定义指令),你可以将它们包裹在内置的 组件中

<ClientOnly>
  <NonSSRFriendlyComponent />
</ClientOnly>

OutboundLink

vuepress一致

用来表明当前是一个外部链接。在 VitePress 中这个组件会紧跟在每一个外部链接后面。

定制

您可以通过添加.vitepress/theme/index.js 文件来开发自定义主题。

.
├─ docs
│  ├─ .vitepress
│  │  ├─ theme
│  │  │  └─ index.js
│  │  └─ config.js
│  └─ index.md
└─ package.json

.vitepress/theme/index.js 中,必须导出主题对象并注册自己的主题布局。假设您有这样的布局组件。

<!-- .vitepress/theme/Layout.vue -->
<template>
  <h1>Custom Layout!</h1>
  <!-- 确保包括markdown出口 -->
  <Content />
</template>

然后将其包含在.vitepress/theme/index.js 中

// .vitepress/theme/index.js
import Layout from './Layout.vue'

export default {
  Layout,
  NotFound: () => 'custom 404', // <- this is a Vue 3 functional component
  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.
  }
}

如果要扩展默认主题,可以从 vitepress/theme 导入它。

// .vitepress/theme/index.js
import DefaultTheme from 'vitepress/theme'

export default {
...DefaultTheme
}

与 VuePress 的区别

通用

  • 去除的

    • 站点配置不支持 YAML 和 TOML 格式。.vitepress/config.js 只支持 javascript
    • 支持插件,功能都实现在主题中
    • 永久链接的支持
    • .vitepress/templates
    • .vitepress/Components 中的组件不会自动注册为全局组件
  • 不同的

    • 公共文件将从.vitepress/public/替换成/public来复制移动到dist
    • 样式 .vitepress/styles/index.styl and .vitepress/styles/palette.styl 使用 .vitepress/style.styl
    • 应用程序级增强 API,App enhancements .vitepress/enhanceApp.js.vitepress/theme/index.js

Markdown

站点设置

默认主题配置

  • 去除的

    • smoothScroll
    • displayAllHeaders
    • activeHeaderLinks
    • sidebarDepth and initialOpenGroupIndex for sidebar groups
  • 不同的

    • searchMaxSuggestions is search.maxSuggestions
    • algolia is search.algolia
    • searchPlaceholder is search.placeholder

默认主题

  • 去除的
    • <code-group> and <code-block>

全局计算属性

  • 去除的
    • $lang
    • $localePath

Frontmatter 预定义的变量

Frontmatter 默认主题变量

siteData

pageData

全局组件

配置

App 配置

base

  • 类型: string
  • 默认值: / 部署站点的基础路径,如果你想让你的网站部署到一个子路径下,你将需要设置它。如 GitHub pages,如果你想将你的网站部署到 foo.github.io/bar/,那么 base 应该被设置成 "/bar/",它的值应当总是以斜杠开始,并以斜杠结束。

base 将会作为前缀自动地插入到所有以 / 开始的其他选项的链接中,所以你只需要指定一次。

module.exports = {
  base: '/base/'
}

lang

  • 类型: string
  • 默认值: en-US 站点的 lang 属性。这将在 html 页面中呈现为标签。
module.exports = {
    lang: 'en-US'
}

title

  • 类型: string
  • 默认值: VitePress 网站的标题。这将是所有页面标题的前缀,并显示在导航栏中。
module.exports = {
    title: 'VitePress'
}

description

  • 类型: string
  • 默认值: A VitePress site 站点的描述。这将在页面 HTML 中呈现为标签。
module.exports = {
    description: 'A VitePress site'
}

主题配置

主页

VitePress 提供了一个主页布局。要使用它,请指定 home: true 加上根索引中的一些其他元数据。md 的 YAML frontmatter。这是它如何工作的一个例子

---
home: true
heroImage: /logo.png
heroAlt: Logo image
heroText: Hero Title
tagline: Hero subtitle
actionText: Get Started
actionLink: /guide/
features:
  - title: Simplicity First
    details: Minimal setup with markdown-centered project structure helps you focus on writing.
  - title: Vue-Powered
    details: Enjoy the dev experience of Vue + webpack, use Vue components in markdown, and develop custom themes with Vue.
  - title: Performant
    details: VitePress generates pre-rendered static HTML for each page, and runs as an SPA once a page is loaded.
footer: MIT Licensed | Copyright © 2019-present Evan You
---

Algolia Search

其实就是有一个搜索框

themeConfig.algolia 选项允许您使用 algolia DocSearch。要启用它,您至少需要提供 apiKey 和 indexNam

要了解更多选项,请查看 Algolia DocSearch 的文档。你可以在其他选项旁边传递任何额外的选项,例如传递 searchParameters

module.exports = {
  themeConfig: {
    algolia: {
      apiKey: 'your_api_key',
      indexName: 'index_name',
      searchParameters: {
        facetFilters: ['tags:guide,api']
      }
    }
  }
}

国际化(i18n)

如果您的文档中有多个地区,并且您已经在 themeConfig 中定义了一个locales对象

module.exports = {
  themeConfig: {
    locales: {
      // ...
    },
    algolia: {
      apiKey: 'your_api_key',
      indexName: 'index_name'
    }
  }
}

VitePress 将自动向 searchParams 添加语言 facetFilter。使用正确的语言值的 facetFilter 数组。通过添加 language 作为 facet 的自定义属性,并基于元素的 lang 属性进行设置,确保正确配置你的 DocSearch 配置。下面是一个简单的 DocSearch 配置示例

{
  "index_name": "<the name of your library>",
  "start_urls": [
    {
      "url": "<your deployed url>"
    }
  ],
  "stop_urls": ["(?:(?<!\\.html)(?<!/))$"],
  "selectors": {
    "lvl0": {
      "selector": ".sidebar > .sidebar-links > .sidebar-link .sidebar-link-item.active",
      "global": true,
      "default_value": "Documentation"
    },
    "lvl1": ".content h1",
    "lvl2": ".content h2",
    "lvl3": ".content h3",
    "lvl4": ".content h4",
    "lvl5": ".content h5",
    "lvl6": ".content p, .content li",
    "text": ".content [class^=language-]",
    "language": {
      "selector": "/html/@lang",
      "type": "xpath",
      "global": true,
      "default_value": "en-US"
    }
  },
  "custom_settings": {
    "attributesForFaceting": ["language"]
  }
}

您可以查看 Vue Router 使用的 DocSearch 配置,以获得一个完整的示例。

Carbon Ads

其实就是一个广告

VitePress 内置了对 Carbon Ads 的原生支持。通过在配置中定义 Carbon Ads 凭证,VitePress 将在页面上显示广告

module.exports = {
  themeConfig: {
    carbonAds: {
      carbon: 'your-carbon-key',
      custom: 'your-carbon-custom',
      placement: 'your-carbon-placement'
    }
  }
}