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:
@ -16,7 +16,7 @@ All referenced assets, including those using absolute paths, will be copied to t
All **static** path references, including absolute paths, should be based on your working directory structure.
## The Public Directory
## public 目录 {#the-public-directory}
Sometimes you may need to provide static assets that are not directly referenced in any of your Markdown or theme components, or you may want to serve certain files with the original filename. Examples of such files include `robot.txt`, favicons, and PWA icons.
@ -31,7 +31,7 @@ There is one exception to this: if you have an HTML page in `public` and link to
- [/pure.html](/pure.html)
- <pathname:///pure.html>
## Base URL
## 根 URL {#base-url}
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).
Connecting VitePress to a CMS will largely revolve around [Dynamic Routes](./routing#dynamic-routes). Make sure to understand how it works before proceeding.
@ -51,6 +51,6 @@ Since each CMS will work differently, here we can only provide a generic workflo
<!-- @content -->
```
## Integration Guides
## 整合指南 {#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!
You can enable a custom theme by creating a `.vitepress/theme/index.js` or `.vitepress/theme/index.ts` file (the "theme entry file"):
@ -17,7 +17,7 @@ You can enable a custom theme by creating a `.vitepress/theme/index.js` or `.vit
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
## 主题接口 {#theme-interface}
A VitePress custom theme is defined as an object with the following interface:
@ -68,7 +68,7 @@ The default export is the only contract for a custom theme, and only the `Layout
Inside your layout component, it works just like a normal Vite + Vue 3 application. Do note the theme also needs to be [SSR-compatible](./ssr-compat).
## Building a Layout
## 构建布局 {#building-a-layout}
The most basic layout component needs to contain a [`<Content />`](../reference/runtime-api#content) component:
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
## Distributing a Custom Theme {#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).
@ -168,7 +168,7 @@ If you wish to distribute the theme as an npm package, follow these steps:
5. Provide clear instructions on how to consume your theme (see below).
## Consuming a Custom Theme
## Consuming a Custom Theme {#consuming-a-custom-theme}
To consume an external theme, import and re-export it from the custom theme entry:
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
## 基本用法 {#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:
@ -52,7 +52,7 @@ export default {
}
```
## Data from 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.
@ -130,7 +130,7 @@ import { data as posts } from './posts.data.js'
</template>
```
### Options
### Options {#options}
The default data may not suit all needs - you can opt-in to transform the data using options:
@ -171,7 +171,7 @@ export default {
}
```
## Typed Data Loaders
## Typed Data Loaders {#typed-data-loaders}
When using TypeScript, you can type your loader and `data` export like so:
The following guides are based on some shared assumptions:
@ -19,7 +19,7 @@ The following guides are based on some shared assumptions:
}
```
## Build and Test Locally
## 本地构建和测试 {#build-and-test-locally}
1. Run this command to build the docs:
@ -47,13 +47,13 @@ The following guides are based on some shared assumptions:
Now the `docs:preview` method will launch the server at `http://localhost:8080`.
## Setting a Public Base Path
## 设定 public 根目录 {#setting-a-public-base-path}
By default, we assume the site is going to be deployed at the root path of a domain (`/`). If your site is going to be served at a sub-path, e.g. `https://mywebsite.com/blog/`, then you need to set the [`base`](../reference/site-config#base) option to `'/blog/'` in the VitePress config.
**Example:** If you're using Github (or GitLab) Pages and deploying to `user.github.io/repo/`, then set your `base` to `/repo/`.
## HTTP Cache Headers
## HTTP 缓存标头 {#http-cache-headers}
If you have control over the HTTP headers on your production server, you can configure `cache-control` headers to achieve better performance on repeated visits.
@ -103,9 +103,9 @@ Note: the `vercel.json` file should be placed at the root of your **repository**
Set up a new project and change these settings using your dashboard:
@ -117,7 +117,7 @@ Set up a new project and change these settings using your dashboard:
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
### GitHub Pages
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.
@ -171,7 +171,7 @@ Don't enable options like _Auto Minify_ for HTML code. It will remove comments f
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
### GitLab Pages
1. Set `outDir` in `docs/.vitepress/config.js` to `../public`.
@ -214,7 +214,7 @@ Don't enable options like _Auto Minify_ for HTML code. It will remove comments f
- main
```
### Azure Static Web Apps
### Azure Static Web Apps {#azure-static-web-apps}
1. Follow the [official documentation](https://docs.microsoft.com/en-us/azure/static-web-apps/build-configuration).
@ -224,7 +224,7 @@ Don't enable options like _Auto Minify_ for HTML code. It will remove comments f
- **`output_location`**: `docs/.vitepress/dist`
- **`app_build_command`**: `npm run docs:build`
### Firebase
### Firebase {#firebase}
1. Create `firebase.json` and `.firebaserc` at the root of your project:
@ -255,7 +255,7 @@ Don't enable options like _Auto Minify_ for HTML code. It will remove comments f
firebase deploy
```
### Surge
### Surge
1. After running `npm run docs:build`, run this command to deploy:
@ -263,7 +263,7 @@ Don't enable options like _Auto Minify_ for HTML code. It will remove comments f
npx surge docs/.vitepress/dist
```
### Heroku
### Heroku
1. Follow documentation and guide given in [`heroku-buildpack-static`](https://elements.heroku.com/buildpacks/heroku/heroku-buildpack-static).
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.
@ -14,7 +14,7 @@ These advanced customizations will require using a custom theme that "extends" t
Before proceeding, make sure to first read [Using a Custom Theme](./custom-theme) to understand how custom themes work.
:::
## Customizing CSS
## 自定义 CSS {#customizing-css}
The default theme CSS is customizable by overriding root level CSS variables:
@ -36,7 +36,7 @@ export default DefaultTheme
See [default theme CSS variables](https://github.com/vuejs/vitepress/blob/main/src/client/theme-default/styles/vars.css) that can be overridden.
## Using Different Fonts
## 使用自定义字体 {#using-different-fonts}
VitePress uses [Inter](https://rsms.me/inter/) as the default font, and will include the fonts in the build output. The font is also auto preloaded in production. However, this may not be desirable if you want to use a different main font.
@ -88,7 +88,7 @@ export default {
}
```
## Registering Global Components
## 注册全局组件 {#registering-global-components}
```js
// .vitepress/theme/index.js
@ -105,7 +105,7 @@ export default {
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
## 布局插槽 {#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:
@ -190,7 +190,7 @@ Full list of slots available in the default theme layout:
- `nav-screen-content-before`
- `nav-screen-content-after`
## Overriding Internal Components
## 重写内部组件 {#overriding-internal-components}
You can use Vite's [aliases](https://vitejs.dev/config/shared-options.html#resolve-alias) to replace default theme components with your custom ones:
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:
@ -15,7 +15,7 @@ Many site or default theme config options have corresponding options in frontmat
You can also define custom frontmatter data of your own, to be used in dynamic Vue expressions on the page.
## Accessing Frontmatter Data
## Accessing Frontmatter Data {#accessing-frontmatter-data}
Frontmatter data can be accessed via the special `$frontmatter` global variable:
You can try VitePress directly in your browser on [StackBlitz](https://vitepress.new).
## Installation
## 安装 {#installation}
### Prerequisites
### 前置知识 {#prerequisites}
- [Node.js](https://nodejs.org/) version 16 or higher.
- Terminal for accessing VitePress via its command line interface (CLI).
@ -46,7 +46,7 @@ If using PNPM, you will notice a missing peer warning for `@docsearch/js`. This
:::
### Setup Wizard
### 安装向导 {#setup-wizard}
VitePress ships with a command line setup wizard that will help you scaffold a basic project. After installation, start the wizard by running:
@ -72,7 +72,7 @@ You will be greeted with a few simple questions:
If you intend to perform customization that uses Vue components or APIs, you should also explicitly install `vue` as a peer dependency.
:::
## File Structure
## 文件结构 {#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.
@ -95,7 +95,7 @@ The `docs` directory is considered the **project root** of the VitePress site. T
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).
:::
### The Config File
### 配置文件 {#the-config-file}
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:
@ -114,7 +114,7 @@ export default {
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
### 源文件 {#source-files}
Markdown files outside the `.vitepress` directory are considered **source files**.
@ -122,7 +122,7 @@ VitePress uses **file-based routing**: each `.md` file is compiled into a corres
VitePress also provides the ability to generate clean URLs, rewrite paths, and dynamically generate pages. These will be covered in the [Routing Guide](./routing).
## Up and Running
## 运行 {#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:
@ -174,7 +174,7 @@ More command line usage is documented in the [CLI Reference](../reference/cli).
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}
- To better understand how markdown files are mapped to generated HTML, proceed to the [Routing Guide](./routing).
**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`.
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.
VitePress comes with built in Markdown Extensions.
## Header Anchors
## 标题锚点 {#header-anchors}
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}
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 `/`.
@ -40,18 +40,18 @@ And providing you are in `foo/one.md`:
[bar - four](../bar/four.html) <!-- or you can append .html -->
```
### Page Suffix
### Page Suffix {#page-suffix}
Pages and internal links get generated with the `.html` suffix by default.
### External Links
### External Links {#external-links}
Outbound links automatically get `target="_blank" rel="noreferrer"`:
- [vuejs.org](https://vuejs.org)
- [VitePress on GitHub](https://github.com/vuejs/vitepress)
## Frontmatter
## Frontmatter {#frontmatter}
[YAML frontmatter](https://jekyllrb.com/docs/front-matter/) is supported out of the box:
@ -66,7 +66,7 @@ This data will be available to the rest of the page, along with all custom and t
For more details, see [Frontmatter](../reference/frontmatter-config).
## GitHub-Style Tables
## GitHub-Style Tables {#github-style-tables}
**Input**
@ -86,7 +86,7 @@ For more details, see [Frontmatter](../reference/frontmatter-config).
| col 2 is | centered | \$12 |
| zebra stripes | are neat | \$1 |
## Emoji :tada:
## Emoji :tada: {#emoji-:tada:}
**Input**
@ -100,7 +100,7 @@ For more details, see [Frontmatter](../reference/frontmatter-config).
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 {#table-of-contents}
**Input**
@ -114,11 +114,11 @@ A [list of all emojis](https://github.com/markdown-it/markdown-it-emoji/blob/mas
Rendering of the TOC can be configured using the `markdown.toc` option.
## Custom Containers
## Custom Containers {#custom-containers}
Custom containers can be defined by their types, titles, and contents.
### Default Title
### Default Title {#default-title}
**Input**
@ -166,7 +166,7 @@ This is a dangerous warning.
This is a details block.
:::
### Custom Title
### Custom Title {#custom-title}
You may set custom title by appending the text right after the "type" of the container.
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.
@ -237,7 +237,7 @@ Wraps in a <div class="vp-raw">
:::
## Syntax Highlighting in Code Blocks
## Syntax Highlighting in Code Blocks {#syntax-highlighting-in-code-blocks}
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:
@ -283,7 +283,7 @@ A [list of valid languages](https://github.com/shikijs/shiki/blob/main/docs/lang
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 {#line-highlighting-in-code-blocks}
**Input**
@ -379,7 +379,7 @@ export default {
}
```
## Focus in Code Blocks
## 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.
@ -413,7 +413,7 @@ export default {
}
```
## Colored Diffs in Code Blocks
## 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.
@ -447,7 +447,7 @@ export default {
}
```
## Errors and Warnings in Code Blocks
## Errors and Warnings in Code Blocks {#errors-and-warnings-in-code-blocks}
Adding the `// [!code warning]` or `// [!code error]` comments on a line will color it accordingly.
@ -481,7 +481,7 @@ export default {
}
```
## Line Numbers
## Line Numbers {#line-numbers}
You can enable line numbers for each code blocks via config:
@ -527,7 +527,7 @@ const line2 = 'This is line 2'
const line3 = 'This is line 3'
```
## Import Code Snippets
## Import Code Snippets {#import-code-snippets}
You can import code snippets from existing files via following syntax:
@ -591,7 +591,7 @@ You can also specify the language inside the braces (`{}`) like this:
This is helpful if source language cannot be inferred from your file extension.
## Code Groups
## Code Groups {#code-groups}
You can group multiple code blocks like this:
@ -679,16 +679,16 @@ You can also [import snippets](#import-code-snippets) in code groups:
You can include a markdown file in another markdown file like this:
**Input**
```md
# Docs
# Docs {#docs}
## Basics
## Basics {#basics}
<!--@include: ./parts/basics.md-->
```
@ -698,7 +698,7 @@ You can include a markdown file in another markdown file like this:
```md
Some getting started stuff.
### Configuration
### Configuration {#configuration}
Can be created using `.foorc.json`.
```
@ -706,13 +706,13 @@ Can be created using `.foorc.json`.
**Equivalent code**
```md
# Docs
# Docs {#docs}
## Basics
## Basics {#basics}
Some getting started stuff.
### Configuration
### Configuration {#configuration}
Can be created using `.foorc.json`.
```
@ -721,7 +721,7 @@ Can be created using `.foorc.json`.
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.
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`:
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` option has changed its structure.
- `children` key is now named `items`.
@ -17,7 +17,7 @@ If you're coming from VitePress 0.x version, there're several breaking changes d
- `lastUpdated` option is now split into `config.lastUpdated` and `themeConfig.lastUpdatedText`.
- `carbonAds.carbon` is changed to `carbonAds.code`.
## Frontmatter Config
## Frontmatter 配置 {#frontmatter-config}
- `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).
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 {#markdown}
### Images
### 图片 {#images}
Unlike VuePress, VitePress handles [`base`](./asset-handling#base-url) of your config automatically when you use static image.
`<script client>` is a VitePress-only feature, not a Vue feature. It works in both `.md` and `.vue` files, but only in MPA mode. Client scripts in all theme components will be bundled together, while client script for a specific page will be split for that page only.
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:
The resulting HTML can be hosted on any web server that can serve static files.
## Root and Source Directory
## 根目录和源目录 {#root-and-source-directory}
There are two important concepts in the file structure of a VitePress project: the **project root** and the **source directory**.
### Project Root
### 项目根目录 {#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.
@ -58,7 +58,7 @@ docs/index.md --> /index.html (accessible as /)
docs/getting-started.md --> /getting-started.html
```
### Source Directory
### 源目录 {#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.
@ -79,7 +79,7 @@ src/index.md --> /index.html (accessible as /)
src/getting-started.md --> /getting-started.html
```
## Linking Between Pages
## 链接页面 {#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.
@ -95,7 +95,7 @@ You can use both absolute and relative paths when linking between pages. Note th
Learn more about linking to assets such images in [Asset Handling](asset-handling).
## Generating Clean URL
## 生成简洁的 URL {#generating-clean-url}
:::warning Server Support Required
To serve clean URLs with VitePress, server-side support is required.
@ -124,7 +124,7 @@ If, however, you cannot configure your server with such support (e.g. GitHub pag
└─ index.md
```
## Route Rewrites
## Route Rewrites {#route-rewrites}
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:
@ -181,11 +181,11 @@ When rewrites are enabled, **relative links should be based on the rewritten pat
```
:::
## Dynamic Routes
## Dynamic Routes {#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
### Paths Loader File {#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):
@ -221,7 +221,7 @@ The generated HTML pages will be:
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.
@ -297,7 +297,7 @@ export default {
}
```
### Accessing Params in Page
### Accessing Params in Page {#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:
@ -319,7 +319,7 @@ console.log(params.value)
</script>
```
### Rendering Raw Content
### Rendering Raw Content {#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.
VitePress pre-renders the app in Node.js during the production build, using Vue's Server-Side Rendering (SSR) capabilities. This means all custom code in theme components are subject to SSR Compatibility.
The [SSR section in official Vue docs](https://vuejs.org/guide/scaling-up/ssr.html) provides more context on what is SSR, the relationship between SSR / SSG, and common notes on writing SSR-friendly code. The rule of thumb is to only access browser / DOM APIs in `beforeMount` or `mounted` hooks of Vue components.
## `<ClientOnly>`
## `<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:
@ -18,11 +18,11 @@ If you are using or demoing components that are not SSR-friendly (for example, c
</ClientOnly>
```
## Libraries that Access Browser API on Import
## 在导入时访问浏览器 API 的库 {#libraries-that-access-browser-api-on-import}
Some components or libraries access browser APIs **on import**. To use code that assumes a browser environment on import, you need to dynamically import them.
### Importing in Mounted Hook
### 在 mounted 钩子中导入 {#importing-in-mounted-hook}
```vue
<scriptsetup>
@ -36,7 +36,7 @@ onMounted(() => {
</script>
```
### Conditional Import
### Conditional Import {#conditional-import}
You can also conditionally import a dependency using the `import.meta.env.SSR` flag (part of [Vite env variables](https://vitejs.dev/guide/env-and-mode.html#env-variables)):
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.
@ -8,9 +8,9 @@ It's worth noting that VitePress leverages Vue's compiler to automatically detec
All Vue usage needs to be SSR-compatible. See [SSR Compatibility](./ssr-compat) for details and common workarounds.
:::
## Templating
## 模板化 {#templating}
### Interpolation
### 插值语法 {#interpolation}
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:
@ -24,7 +24,7 @@ Each Markdown file is first compiled into HTML and then passed on as a Vue compo
Directives also work (note that by design, raw HTML is also valid in Markdown):
@ -38,7 +38,7 @@ Directives also work (note that by design, raw HTML is also valid in Markdown):
<divclass="language-text"><pre><code><spanv-for="i in 3">{{ i }} </span></code></pre></div>
## `<script>` and `<style>`
## `<script>` and `<style>` {#`<script>`-and-`<style>`}
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:
@ -53,7 +53,7 @@ import { ref } from 'vue'
const count = ref(0)
</script>
## Markdown Content
## Markdown Content {#markdown-content}
The count is: {{ count }}
@ -96,11 +96,11 @@ const { page } = useData()
}
```
## Using Components
## 使用组件 {#using-components}
You can import and use Vue components directly in Markdown files.
### Importing in Markdown
### 在 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:
@ -120,7 +120,7 @@ This is a .md using a custom component
...
```
### Registering Components Globally
### 注册全局组件 {#registering-components-globally}
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](./extending-default-theme#registering-global-components) for an example.
@ -128,7 +128,7 @@ If a component is going to be used on most of the pages, they can be registered
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.
:::
### Using Components In Headers <ComponentInHeader/>
You can use Vue components in the headers, but note the difference between the following syntaxes:
@ -144,7 +144,7 @@ The output HTML is accomplished by [Markdown-it](https://github.com/Markdown-it/
:::
## Escaping
## 转义 {#escaping}
You can escape Vue interpolations by wrapping them in a `<span>` or other elements with the `v-pre` directive:
@ -178,7 +178,7 @@ Alternatively, you can wrap the entire paragraph in a `v-pre` custom container:
</div>
## Unescape in Code Blocks
## 代码块中不转义 {#unescape-in-code-blocks}
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`:
@ -196,18 +196,18 @@ Hello {{ 1 + 1 }}
Hello {{ 1 + 1 }}
```
## Using CSS Pre-processors
## 使用 CSS 预处理器 {#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
# .scss and .sass {#.scss-and-.sass}
npm install -D sass
# .less
# .less {#.less}
npm install -D less
# .styl and .stylus
# .styl and .stylus {#.styl-and-.stylus}
npm install -D stylus
```
@ -220,7 +220,7 @@ Then you can use the following in Markdown and theme components:
</style>
```
## Using Teleports
## 传递组件内容 {#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).
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.
@ -8,7 +8,7 @@ Just want to try it out? Skip to the [Quickstart](./getting-started).
</div>
## Use Cases
## 使用场景 {#use-cases}
- **Documentation**
@ -22,7 +22,7 @@ Just want to try it out? Skip to the [Quickstart](./getting-started).
The official [Vue.js blog](https://blog.vuejs.org/) is a simple blog that generates its index page based on local content.
## Developer Experience
## 开发体验 {#developer-experience}
VitePress aims to provide a great Developer Experience (DX) when working with Markdown content.
@ -32,7 +32,7 @@ VitePress aims to provide a great Developer Experience (DX) when working with Ma
- **[Vue-Enhanced Markdown](./using-vue):** each Markdown page is also a Vue [Single-File Component](https://vuejs.org/guide/scaling-up/sfc.html), thanks to Vue template's 100% syntax compatibility with HTML. You can embed interactivity in your static content using Vue templating features or imported Vue components.
## Performance
## 性能 {#performance}
Unlike many traditional SSGs, a website generated by VitePress is in fact a [Single Page Application](https://en.wikipedia.org/wiki/Single-page_application) (SPA).
@ -48,7 +48,7 @@ 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.
## What About VuePress?
## VuePress 怎么样? {#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.
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
### 用法 {#usage}
```sh
# start in current directory, omitting `dev`
# start in current directory, omitting `dev` {#start-in-current-directory,-omitting-`dev`}
vitepress
# start in sub directory
# start in sub directory {#start-in-sub-directory}
vitepress dev [root]
```
### Options
### 选项 {#options}
| Option | Description |
| - | - |
@ -25,17 +25,17 @@ vitepress dev [root]
| `--strictPort` | Exit if specified port is already in use (`boolean`) |
| `--force` | Force the optimizer to ignore the cache and re-bundle (`boolean`) |
## `vitepress build`
## `vitepress build` {#`vitepress-build`}
Build the VitePress site for production.
### Usage
### 用法 {#usage}
```sh
vitepress build [root]
```
### Options
### 选项 {#options}
| Option | Description |
| - | - |
@ -46,28 +46,28 @@ vitepress build [root]
| `--minify [minifier]` | Enable/disable minification, or specify minifier to use (default: `"esbuild"`) (`boolean \| "terser" \| "esbuild"`) |
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.
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.
@ -49,7 +49,7 @@ export default {
}
```
## Frontmatter Config
## Frontmatter 配置 {#frontmatter-config}
This can be disabled per-page using the `editLink` option on frontmatter:
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).
@ -10,7 +10,7 @@ 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
## Hero 部分 {#hero-section}
The Hero section comes at the top of the homepage. Here's how you can configure the Hero section.
@ -72,7 +72,7 @@ interface HeroAction {
}
```
### Customizing the name color
### 自定义名字的颜色 {#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.
@ -91,7 +91,7 @@ Also you may customize it further by combining `--vp-home-hero-name-background`
}
```
## Features Section
## Features 部分 {#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 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.
@ -8,7 +8,7 @@ layout: doc
---
```
## Doc 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.
@ -21,7 +21,7 @@ It also provides documentation specific features listed below. These features ar
- Outline
- [Carbon Ads](./default-theme-carbon-ads)
## Page Layout
## page 布局 {#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.
@ -29,10 +29,10 @@ The page layout will let you style everything by you without VitePress theme aff
Note that even in this layout, sidebar will still show up if the page has a matching sidebar config.
## Home Layout
## Home 布局 {#home-layout}
Option `home` will generate templated "Homepage". In this layout, you can set extra options such as `hero` and `features` to customize the content further. Please visit [Default Theme: Home Page](./default-theme-home-page) for more details.
## No Layout
## 无布局 {#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).
The Nav is the navigation bar displayed on top of the page. It contains the site title, global menu links, etc.
## Site Title and Logo
## 站点标题和 logo {#site-title-and-logo}
By default, nav shows the title of the site referencing [`config.title`](./site-config#title) value. If you would like to change what's displayed on nav, you may define custom text in `themeConfig.siteTitle` option.
@ -37,7 +37,7 @@ export default {
You can also pass an object as logo if you want to add `alt` attribute or customize it based on dark/light mode. Refer [`themeConfig.logo`](./default-theme-config#logo) for details.
## Navigation Links
## 导航链接 {#navigation-links}
You may define `themeConfig.nav` option to add links to your nav.
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.
@ -138,7 +138,7 @@ export default {
`activeMatch` is expected to be a regex string, but you must define it as a string. We can't use actual RegExp object here because it isn't serializable during the build time.
:::
### Customize link's "target" and "rel" attributes
By default, VitePress automatically determines `target` and `rel` attributes based on whether the link is an external link. But if you want, you can customize them too.
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.
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:
The sidebar is the main navigation block for your documentation. You can configure the sidebar menu in [`themeConfig.sidebar`](./default-theme-config#sidebar).
@ -19,7 +19,7 @@ export default {
}
```
## The Basics
## 基本用法 {#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.
@ -93,7 +93,7 @@ export default {
}
```
## Multiple Sidebars
## 多侧边栏 {#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.
@ -147,7 +147,7 @@ export default {
}
```
## Collapsible Sidebar Groups
## 可折叠的侧边栏组 {#collapsible-sidebar-groups}
By adding `collapsed` option to the sidebar group, it shows a toggle button to hide/show each section.
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}
You may use `<VPTeamMembers>` component exposed from `vitepress/theme` to display a list of team members on any page.
@ -66,7 +66,7 @@ Embedding team members in doc page is good for small size team where having dedi
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}
Instead of adding team members to doc page, you may also create a full Team Page, similar to how you can create a custom [Home Page](./default-theme-home-page).
@ -119,7 +119,7 @@ When creating a full team page, remember to wrap all components with `<VPTeamPag
`<VPMembers>` works as same as when used in a doc page. It will display list of members.
You may add "sections" to the team page. For example, you may have different types of team members such as Core Team Members and Community Partners. You can divide these members into sections to better explain the roles of each group.
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.
@ -21,7 +21,7 @@ You can access frontmatter data via the `$frontmatter` global in Vue expressions
{{ $frontmatter.title }}
```
## title
## title {#title}
- Type: `string`
@ -82,11 +82,11 @@ type HeadConfig =
| [string, Record<string,string>, string]
```
## Default Theme Only
## 仅在默认主题生效 {#default-theme-only}
The following frontmatter options are only applicable when using the default theme.
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.
@ -6,7 +6,7 @@ The helper methods are globally importable from `vitepress` and are typically us
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>`.
Site config is where you can define the global settings of the site. App config options define settings that apply to every VitePress site, regardless of what theme it is using. For example, the base directory or the title of the site.
## Overview
## 概览 {#overview}
### Config Resolution
### 配置解析 {#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`.
@ -24,7 +24,7 @@ export default {
}
```
### Config Intellisense
### 配置提示 {#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.
@ -36,7 +36,7 @@ export default defineConfig({
})
```
### Typed Theme Config
### 主题类型提示 {#typed-theme-config}
By default, `defineConfig` helper expects the theme config type from default theme:
You can configure the underlying [Markdown-It](https://github.com/markdown-it/markdown-it) instance using the [markdown](#markdown) option in your VitePress config.
## Site Metadata
## 站点元数据 {#site-metadata}
### title
@ -132,7 +132,6 @@ Here `:title` will be replaced with the text inferred from the page's first `<h1
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)
@ -199,7 +198,7 @@ export default {
}
```
## Routing
## 路由 {#routing}
### cleanUrls
@ -226,7 +225,7 @@ export default {
}
```
## Build
## 构建 {#build}
### srcDir
@ -300,7 +299,7 @@ export default {
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
## 主题化 {#theming}
### appearance
@ -316,7 +315,6 @@ Whether to enable dark mode (by adding the `.dark` class to the `<html>` element
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`
@ -324,7 +322,7 @@ Whether to get the last updated timestamp for each page using Git. The timestamp
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
## 自定义 {#customization}
### markdown
@ -434,7 +432,7 @@ export default {
}
```
## Build Hooks
## 构建钩子 {#build-hooks}
VitePress build hooks allow you to add new functionality and behaviors to your website: