### Initialize VitePress Project Source: https://vitepress.dev/reference/cli Launch the setup wizard to configure a new VitePress project. ```sh vitepress init ``` -------------------------------- ### Run Setup Wizard Source: https://vitepress.dev/guide/getting-started Initialize a new VitePress project using the built-in command line wizard. ```sh $ npx vitepress init ``` ```sh $ pnpm vitepress init ``` ```sh $ yarn vitepress init ``` ```sh $ bun vitepress init ``` -------------------------------- ### Start VitePress Dev Server with npm Source: https://vitepress.dev/guide/getting-started Use this command to start a local development server with instant hot updates for your VitePress site. Ensure you have the 'docs:dev' script configured in your package.json. ```sh $ npm run docs:dev ``` ```sh $ pnpm run docs:dev ``` ```sh $ yarn docs:dev ``` ```sh $ bun run docs:dev ``` -------------------------------- ### Install VitePress Source: https://vitepress.dev/guide/getting-started Install VitePress as a development dependency using your preferred package manager. ```sh $ npm add -D vitepress@next ``` ```sh $ pnpm add -D vitepress@next ``` ```sh $ yarn add -D vitepress@next vue ``` ```sh $ bun add -D vitepress@next ``` -------------------------------- ### Custom Page CSS Example Source: https://vitepress.dev/reference/frontmatter-config Example of how to style a page using a custom class defined in frontmatter. ```css .custom-page-class { /* page-specific styles */ } ``` -------------------------------- ### Start VitePress Development Server Source: https://vitepress.dev/reference/cli Run the development server in the current directory or a specified subdirectory. ```sh # start in current directory, omitting `dev` vitepress # start in sub directory vitepress dev [root] ``` -------------------------------- ### Install MathJax dependency Source: https://vitepress.dev/guide/markdown Install the required markdown-it-mathjax3 package via npm. ```sh npm add -D markdown-it-mathjax3@^4 ``` -------------------------------- ### Add Markdown Content and Initialize Project Source: https://vitepress.dev/reference/default-theme-home-page Example of adding custom Markdown content below the frontmatter and using the VitePress CLI to initialize a project. ```md --- layout: home hero: name: VitePress text: Vite & Vue powered static site generator. --- ## Getting Started You can get started using VitePress right away using `npx`! ```sh npm init npx vitepress init ``` ``` -------------------------------- ### vitepress dev Source: https://vitepress.dev/reference/cli Starts the VitePress development server. ```APIDOC ## CLI Command: vitepress dev ### Description Starts the VitePress development server using the designated directory as the root. ### Usage `vitepress dev [root]` ### Options - **--open [path]** (boolean | string) - Open browser on startup - **--port ** (number) - Specify port - **--base ** (string) - Public base path (default: /) - **--cors** (boolean) - Enable CORS - **--strictPort** (boolean) - Exit if specified port is already in use - **--force** (boolean) - Force the optimizer to ignore the cache and re-bundle ``` -------------------------------- ### Monorepo source directory structure Source: https://vitepress.dev/guide/routing Example of a monorepo structure with documentation files located alongside source code. ```text . └─ packages ├─ pkg-a │ └─ src │ ├─ foo.md │ └─ index.md └─ pkg-b └─ src ├─ bar.md └─ index.md ``` -------------------------------- ### Example output format Source: https://vitepress.dev/guide/data-loading The serialized JSON output available to the client. ```json { "hello": "world" } ``` -------------------------------- ### Install CSS Pre-processors Source: https://vitepress.dev/guide/using-vue Install the necessary package for your chosen CSS pre-processor (Sass, Less, Stylus) to use it with VitePress. This is required before using pre-processor syntax in your project. ```bash # .scss and .sass npm install -D sass # .less npm install -D less # .styl and .stylus npm install -D stylus ``` -------------------------------- ### Default Custom Container Examples Source: https://vitepress.dev/guide/markdown Shows the basic usage of custom containers like info, tip, warning, danger, and details. These render as distinct blocks in the output. ```markdown ::: info This is an info box. ::: ::: tip This is a tip. ::: ::: warning This is a warning. ::: ::: danger This is a dangerous warning. ::: ::: details This is a details block. ::: ``` -------------------------------- ### Install PostCSS for Style Isolation Source: https://vitepress.dev/guide/markdown Install PostCSS as a development dependency to enable style isolation. This is a prerequisite for using VitePress's style isolation features. ```sh $ npm add -D postcss ``` -------------------------------- ### Example: Add og:image Meta Tag with transformHead Source: https://vitepress.dev/reference/site-config This example demonstrates how to dynamically add an 'og:image' meta tag to the head of each page using the transformHead hook, avoiding overhead during development. ```typescript export default { async transformHead(context) { if (context.page === '404.md') { return } // The implementation details of `generatePageImage` would depend // on your requirements. Here we assume it generates a suitable // image for each page and returns the image URL. const imageUrl = await generatePageImage(context) return [[ 'meta', { name: 'og:image', content: imageUrl } ]] } } ``` -------------------------------- ### Importing Vue Components in Markdown Source: https://vitepress.dev/guide/using-vue Explicitly import components in the script setup block for code-splitting efficiency. ```md # Docs This is a .md using a custom component ## More docs ... ``` -------------------------------- ### JSON Frontmatter Example Source: https://vitepress.dev/guide/frontmatter VitePress also supports JSON frontmatter, which must start and end with curly braces and be valid JSON. ```json --- { "title": "Blogging Like a Hacker", "editLink": true } --- ``` -------------------------------- ### Paths Loader for Multiple Route Parameters Source: https://vitepress.dev/guide/routing Define routes with multiple dynamic parameters by returning an array of objects, each containing a `params` object with the corresponding keys. This example shows routes for `[pkg]-[version]`. ```javascript 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' }} ] } ``` -------------------------------- ### YAML Frontmatter Example Source: https://vitepress.dev/guide/markdown Shows how to use YAML frontmatter to define metadata for a Markdown page. This data is accessible within the page. ```yaml --- title: Blogging Like a Hacker lang: en-US --- ``` -------------------------------- ### Basic YAML Frontmatter Example Source: https://vitepress.dev/guide/frontmatter Use YAML frontmatter at the beginning of a Markdown file to define page-level metadata. Ensure it's valid YAML enclosed in triple-dashed lines. ```markdown --- title: Docs with VitePress editLink: true --- ``` -------------------------------- ### Vue Script and Style Blocks in Markdown Source: https://vitepress.dev/guide/using-vue Integrate script setup and module styles directly into Markdown files after the frontmatter. ```html --- hello: world --- ## Markdown Content The count is: {{ count }} ``` -------------------------------- ### Internal Link Examples Source: https://vitepress.dev/guide/markdown Demonstrates various ways to create internal links within a VitePress project, including linking to the root, directory indexes, and specific headings. ```markdown [Home](/) [foo](/foo/) [foo heading](./#heading) [bar - three](../bar/three) [bar - three](../bar/three.md) [bar - four](../bar/four.html) ``` -------------------------------- ### Accessing VitePress Runtime APIs Source: https://vitepress.dev/guide/using-vue Use the useData helper to access page metadata within a script setup block. ```html
{{ page }}
``` -------------------------------- ### Algolia Crawler Configuration Source: https://vitepress.dev/reference/default-theme-search This JavaScript snippet provides an example configuration for the Algolia crawler, similar to what is used by the VitePress site. ```javascript module.exports = { // ... other crawler options // Example: include only markdown files include: [ { pattern: '**/*.md' } ], // Example: exclude specific directories exclude: [ '**/node_modules/**', '**/dist/**' ] } ``` -------------------------------- ### Global Custom Container Labels Configuration Source: https://vitepress.dev/guide/markdown Example of configuring custom labels for containers globally in `config.ts`. This is useful for non-English sites. ```typescript // config.ts export default defineConfig({ // ... markdown: { container: { tipLabel: '提示', warningLabel: '警告', dangerLabel: '危险', infoLabel: '信息', detailsLabel: '详细信息' } } // ... }) ``` -------------------------------- ### Set Base URL for Deployment Source: https://vitepress.dev/reference/site-config Specify the base URL path for site deployment, essential for subpath deployments like GitHub Pages. Must start and end with a slash. ```ts export default { base: '/base/' } ``` -------------------------------- ### Configure PostCSS for Style Isolation Source: https://vitepress.dev/guide/markdown Create a `postcss.config.mjs` file and import `postcssIsolateStyles` to configure style isolation. This setup helps prevent style conflicts by isolating component styles. ```js import { postcssIsolateStyles } from 'vitepress' export default { plugins: [postcssIsolateStyles()] } ``` -------------------------------- ### Site Title Configuration Example Source: https://vitepress.dev/reference/site-config Set the global site title. This value is used as a suffix for page titles and in the default theme's nav bar. It can be overridden per page using frontmatter. ```javascript export default { title: 'My Awesome Site' } ``` -------------------------------- ### Use CSS Pre-processors in Vue Components Source: https://vitepress.dev/guide/using-vue Apply CSS pre-processor syntax within ` ``` -------------------------------- ### Build and Preview Commands Source: https://vitepress.dev/guide/deploy Commands to generate the static site and serve it locally for verification. ```sh $ npm run docs:build ``` ```sh $ npm run docs:preview ``` -------------------------------- ### Preview Production Build Source: https://vitepress.dev/reference/cli Serve the production build locally for testing. ```sh vitepress preview [root] ``` -------------------------------- ### Configure Build and Preview Scripts Source: https://vitepress.dev/guide/deploy Add these scripts to your package.json to enable building and local previewing of your documentation. ```json { "scripts": { "docs:build": "vitepress build docs", "docs:preview": "vitepress preview docs" } } ``` -------------------------------- ### Use createContentLoader helper Source: https://vitepress.dev/guide/data-loading Simplify indexing content collections like blog posts using the createContentLoader helper. ```js import { createContentLoader } from 'vitepress' export default createContentLoader('posts/*.md', /* options */) ``` -------------------------------- ### vitepress init Source: https://vitepress.dev/reference/cli Initializes a new VitePress project. ```APIDOC ## CLI Command: vitepress init ### Description Starts the Setup Wizard in the current directory to initialize a new VitePress project. ### Usage `vitepress init` ``` -------------------------------- ### Accessing Site Data with useData Source: https://vitepress.dev/reference/runtime-api Use the `useData` composable to access page-specific data, including site-level metadata, theme configuration, and page details. This function is a Vue 3 Composition API function and should be used within `setup()` or ` ``` -------------------------------- ### Manual Fetch for CI/CD Builds Source: https://vitepress.dev/reference/default-theme-last-updated Prepend a git fetch command to the build script if shallow cloning cannot be disabled in the CI environment. ```json "docs:build": "git fetch --unshallow && vitepress build docs" ``` -------------------------------- ### VitePress Page Metadata Output Source: https://vitepress.dev/guide/using-vue Example of the JSON structure returned by the page metadata helper. ```json { "path": "/using-vue.html", "title": "Using Vue in Markdown", "frontmatter": {}, ... } ``` -------------------------------- ### Dynamic (Async) Site Configuration Source: https://vitepress.dev/reference/site-config Load site configuration dynamically by exporting an async function. This is useful for fetching data, like blog posts, to build parts of your configuration at runtime. ```javascript import { defineConfig } from 'vitepress' export default async () => { const posts = await (await fetch('https://my-cms.com/blog-posts')).json() return defineConfig({ // app level config options lang: 'en-US', title: 'VitePress', description: 'Vite & Vue powered static site generator.', // theme level config options themeConfig: { sidebar: [ ...posts.map((post) => ({ text: post.name, link: `/posts/${post.name}` })) ] } }) } ``` -------------------------------- ### Enable Home Layout Source: https://vitepress.dev/reference/default-theme-home-page Set the layout to home in the page frontmatter to activate the default homepage template. ```yaml --- layout: home --- ``` -------------------------------- ### Set Page Layout to Doc Source: https://vitepress.dev/reference/default-theme-layout Use the `layout: doc` frontmatter to apply the default documentation styling. ```yaml --- layout: doc --- ``` -------------------------------- ### Build VitePress for Production Source: https://vitepress.dev/reference/cli Generate a production-ready build of the site. ```sh vitepress build [root] ``` -------------------------------- ### vitepress preview Source: https://vitepress.dev/reference/cli Locally previews the production build. ```APIDOC ## CLI Command: vitepress preview ### Description Locally previews the production build of the site. ### Usage `vitepress preview [root]` ### Options - **--base ** (string) - Public base path (default: /) - **--port ** (number) - Specify port ``` -------------------------------- ### Override Line Number Settings Source: https://vitepress.dev/guide/markdown Control line number visibility and starting values per code block using block metadata. ```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' ``` ```ts:line-numbers=2 {1} // line-numbers is enabled and start from 2 const line3 = 'This is line 3' const line4 = 'This is line 4' ``` ``` ```ts ```ts {1} // line-numbers is disabled by default const line2 = 'This is line 2' const line3 = 'This is line 3' ``` ``` ```ts ```ts:line-numbers {1} // line-numbers is enabled const line2 = 'This is line 2' const line3 = 'This is line 3' ``` ``` ```ts ```ts:line-numbers=2 {1} // line-numbers is enabled and start from 2 const line3 = 'This is line 3' const line4 = 'This is line 4' ``` ``` -------------------------------- ### Configure Markdown Parser Source: https://vitepress.dev/reference/site-config Pass options to the Markdown-it parser and Shiki for syntax highlighting. ```js export default { markdown: {...} } ``` -------------------------------- ### Define Directory Structure Source: https://vitepress.dev/guide/i18n Organize documentation files by language subdirectories. ```text docs/ ├─ es/ │ ├─ foo.md ├─ fr/ │ ├─ foo.md ├─ foo.md ``` -------------------------------- ### TypeScript Typed Data Loader Example Source: https://vitepress.dev/guide/data-loading Define custom data types and use `defineLoader` for type-checked loader options and data loading in TypeScript projects. ```ts import { defineLoader } from 'vitepress' export interface Data { // data type } declare const data: Data export { data } export default defineLoader({ // type checked loader options watch: ['...'], async load(): Promise { // ... } }) ``` -------------------------------- ### Create a Full Team Page Structure Source: https://vitepress.dev/reference/default-theme-team-page Construct a dedicated team page by using the `` component as a wrapper. This component ensures proper layout for nested team components. Import `VPTeamPage`, `VPTeamPageTitle`, and `VPTeamMembers` from `vitepress/theme`. ```html --- layout: page --- ``` -------------------------------- ### Configure Preview Port Source: https://vitepress.dev/guide/deploy Customize the local preview server port by modifying the preview script. ```json { "scripts": { "docs:preview": "vitepress preview docs --port 8080" } } ``` -------------------------------- ### GitHub Actions Workflow for GitHub Pages Source: https://vitepress.dev/guide/deploy Automates building and deploying a VitePress site to GitHub Pages on pushes to the main branch. ```yaml # Sample workflow for building and deploying a VitePress site to GitHub Pages # name: Deploy VitePress site to Pages on: # Runs on pushes targeting the `main` branch. Change this to `master` if you're # using the `master` branch as the default branch. push: branches: [main] # Allows you to run this workflow manually from the Actions tab workflow_dispatch: # Sets permissions of the GITHUB_TOKEN to allow deployment to GitHub Pages permissions: contents: read pages: write id-token: write # Allow only one concurrent deployment, skipping runs queued between the run in-progress and latest queued. # However, do NOT cancel in-progress runs as we want to allow these production deployments to complete. concurrency: group: pages cancel-in-progress: false jobs: # Build job build: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v5 with: fetch-depth: 0 # Not needed if lastUpdated is not enabled # - uses: pnpm/action-setup@v4 # Uncomment this block if you're using pnpm # with: # version: 9 # Not needed if you've set "packageManager" in package.json # - uses: oven-sh/setup-bun@v1 # Uncomment this if you're using Bun - name: Setup Node uses: actions/setup-node@v6 with: node-version: 24 cache: npm # or pnpm / yarn - name: Setup Pages uses: actions/configure-pages@v4 - name: Install dependencies run: npm ci # or pnpm install / yarn install / bun install - name: Build with VitePress run: npm run docs:build # or pnpm docs:build / yarn docs:build / bun run docs:build - name: Upload artifact uses: actions/upload-pages-artifact@v3 with: path: docs/.vitepress/dist # Deployment job deploy: environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} needs: build runs-on: ubuntu-latest name: Deploy steps: - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v4 ``` -------------------------------- ### Configure Features Section Source: https://vitepress.dev/reference/default-theme-home-page Define a list of features with icons, titles, and descriptions in the frontmatter. ```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... --- ``` -------------------------------- ### Use useLayout Composable Source: https://vitepress.dev/reference/default-theme-config Import and use the `useLayout` composable to access layout-related data such as sidebar visibility. This example shows how to conditionally render content based on whether a sidebar exists. ```vue ``` -------------------------------- ### Customize Prev Link Text and URL Source: https://vitepress.dev/reference/default-theme-prev-next-links Use this frontmatter to specify both custom text and a custom URL for the previous page link. ```yaml --- prev: text: 'Markdown' link: '/guide/markdown' --- ``` -------------------------------- ### Define a basic data loader Source: https://vitepress.dev/guide/data-loading Create a .data.js or .data.ts file with a default export containing a load method. ```js export default { load() { return { hello: 'world' } } } ``` -------------------------------- ### Configure Netlify Redirects Source: https://vitepress.dev/guide/i18n Redirect users to language-specific paths based on headers. ```text /* /es/:splat 302 Language=es /* /fr/:splat 302 Language=fr /* /en/:splat 302 ``` -------------------------------- ### Create a Team Page Title Section Source: https://vitepress.dev/reference/default-theme-team-page Use `` within `` to add a title and lead section to your team page. Utilize the `#title` and `#lead` slots for content. ```html ``` -------------------------------- ### Netlify Custom Headers Source: https://vitepress.dev/guide/deploy Configure cache headers for Netlify by placing this file in the public directory. ```text /assets/* cache-control: max-age=31536000 cache-control: immutable ``` -------------------------------- ### Deploy VitePress to Surge Source: https://vitepress.dev/guide/deploy Use this command to deploy your VitePress project's build output to Surge. Ensure you have run `npm run docs:build` first. ```sh npx surge docs/.vitepress/dist ``` -------------------------------- ### Configure route rewrites Source: https://vitepress.dev/guide/routing Mapping source file paths to desired output URLs using the rewrites configuration option. ```ts export default { rewrites: { 'packages/pkg-a/src/index.md': 'pkg-a/index.md', 'packages/pkg-a/src/foo.md': 'pkg-a/foo.md', 'packages/pkg-b/src/index.md': 'pkg-b/index.md', 'packages/pkg-b/src/bar.md': 'pkg-b/bar.md' } } ``` ```ts export default { rewrites: { 'packages/:pkg/src/:slug*': ':pkg/:slug*' } } ``` ```ts export default { rewrites(id) { return id.replace(/^packages\/([^/]+)\/src\//, '$1/') } } ``` -------------------------------- ### Configure VitePress Source: https://vitepress.dev/guide/getting-started Define site-level and theme-level options in the configuration file. ```js export default { // site-level options title: 'VitePress', description: 'Just playing around.', themeConfig: { // theme-level options } } ``` -------------------------------- ### Custom Container with Additional Attributes Source: https://vitepress.dev/guide/markdown Shows how to add attributes like `open` to custom containers using markdown-it-attrs syntax, enabling features like initially expanded details blocks. ```markdown ::: details Click me to toggle the code {open} ```js console.log('Hello, VitePress!') ``` ::: ``` -------------------------------- ### Using defineConfig for Intellisense Source: https://vitepress.dev/reference/site-config Employ the `defineConfig` helper to enable TypeScript-powered autocompletion and type checking for your VitePress configuration options. This improves developer experience and reduces errors. ```javascript import { defineConfig } from 'vitepress' export default defineConfig({ // ... }) ``` -------------------------------- ### vitepress build Source: https://vitepress.dev/reference/cli Builds the VitePress site for production. ```APIDOC ## CLI Command: vitepress build ### Description Builds the VitePress site for production deployment. ### Usage `vitepress build [root]` ### Options - **--mpa** (boolean) - Build in MPA mode without client-side hydration - **--base ** (string) - Public base path (default: /) - **--target ** (string) - Transpile target (default: "modules") - **--outDir ** (string) - Output directory relative to cwd (default: /.vitepress/dist) - **--assetsInlineLimit ** (number) - Static asset base64 inline threshold in bytes (default: 4096) ``` -------------------------------- ### Basic Site Configuration Source: https://vitepress.dev/reference/site-config Define global settings for your VitePress site, such as language, title, and description. This is the standard way to configure your application. ```javascript export default { // app level config options lang: 'en-US', title: 'VitePress', description: 'Vite & Vue powered static site generator.', ... } ``` -------------------------------- ### Configure Sitemap Options Source: https://vitepress.dev/guide/sitemap-generation Pass additional options supported by the sitemap module directly to the sitemap configuration object. ```ts export default { sitemap: { hostname: 'https://example.com', lastmodDateOnly: false } } ``` -------------------------------- ### Create Code Groups Source: https://vitepress.dev/guide/markdown Organize multiple code blocks into a tabbed interface. ```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 ``` ::: ``` ```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 ``` ::: ``` ```md ::: code-group <<< @/snippets/snippet.js <<< @/snippets/snippet-with-region.js#snippet{1,2 ts:line-numbers} [snippet with region] ::: ``` ```md ::: code-group <<< @/snippets/snippet.js <<< @/snippets/snippet-with-region.js#snippet{1,2 ts:line-numbers} \[snippet with region] ::: ``` -------------------------------- ### GitHub-Style Table Markdown Source: https://vitepress.dev/guide/markdown Illustrates the Markdown syntax for creating tables with alignment options for columns, similar to GitHub Flavored Markdown. ```markdown | Tables | Are | Cool | | ------------- | :-----------: | ----: | | col 3 is | right-aligned | $1600 | | col 2 is | centered | $12 | | zebra stripes | are neat | $1 | ``` -------------------------------- ### withBase Source: https://vitepress.dev/reference/runtime-api Appends the configured base URL to a given path. ```APIDOC ## withBase ### Description Appends the configured base path to a given URL string. ### Parameters - **path** (string) - The path to append the base to. ### Returns - **string** - The full URL path. ``` -------------------------------- ### Configure Cache-Control Header Source: https://vitepress.dev/guide/deploy Set strong cache headers for hashed assets to improve performance. ```text Cache-Control: max-age=31536000,immutable ``` -------------------------------- ### Enable MathJax in config Source: https://vitepress.dev/guide/markdown Set the math property to true in the VitePress configuration file. ```ts export default { markdown: { math: true } } ``` -------------------------------- ### Enable Sitemap Generation Source: https://vitepress.dev/guide/sitemap-generation Configure the hostname in the VitePress configuration file to enable sitemap generation. ```ts export default { sitemap: { hostname: 'https://example.com' } } ``` -------------------------------- ### Customize Next Link Text and URL Source: https://vitepress.dev/reference/default-theme-prev-next-links Configure both the display text and the target URL for the next page link using this frontmatter structure. ```yaml --- next: text: 'Next Section' link: '/guide/next-section' --- ``` -------------------------------- ### Custom Title and Content in Containers Source: https://vitepress.dev/guide/markdown Demonstrates how to set a custom title for containers and embed content, including code blocks within details containers. ```markdown ::: danger STOP Danger zone, do not proceed ::: ::: details Click me to toggle the code ```js console.log('Hello, VitePress!') ``` ::: ``` -------------------------------- ### Set Build Output Directory Source: https://vitepress.dev/reference/site-config Configure the directory where the site build output will be placed. ```ts export default { outDir: '../public' } ``` -------------------------------- ### Render a blog index page Source: https://vitepress.dev/guide/data-loading Iterate over the loaded content data to display a list of posts. ```vue ``` -------------------------------- ### Import Code Snippets Source: https://vitepress.dev/guide/markdown Include external files or specific regions of files into documentation. ```md <<< @/filepath ``` ```md <<< @/filepath{highlightLines} ``` ```md <<< @/snippets/snippet.js{2} ``` ```md <<< @/snippets/snippet.js ``` ```md <<< @/snippets/snippet.js{2} ``` ```md <<< ../snippets/snippet.js ``` ```md <<< @/snippets/snippet-with-region.js#snippet{1} ``` ```md <<< @/snippets/snippet-with-region.js ``` ```md <<< @/snippets/snippet-with-region.js#snippet{1} ``` ```md <<< @/snippets/snippet.cs{c#} <<< @/snippets/snippet.cs{1,2,4-6 c#} <<< @/snippets/snippet.cs{1,2,4-6 c#:line-numbers} ``` -------------------------------- ### Define multiple sidebars Source: https://vitepress.dev/reference/default-theme-sidebar Use an object to map specific directory paths to different sidebar configurations. ```javascript 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' } ] } ] } } } ``` -------------------------------- ### Configure sidebar links with directory index Source: https://vitepress.dev/reference/default-theme-sidebar Use a trailing slash in the link path to automatically target the index.md file within a directory. ```javascript export default { themeConfig: { sidebar: [ { text: 'Guide', items: [ // This shows `/guide/index.md` page. { text: 'Introduction', link: '/guide/' } ] } ] } } ``` -------------------------------- ### Configure Google Analytics Source: https://vitepress.dev/reference/site-config Set up Google Analytics by including the gtag.js script and configuration code in the HTML head. ```ts export default { head: [ [ 'script', { async: '', src: 'https://www.googletagmanager.com/gtag/js?id=TAG_ID' } ], [ 'script', {}, "window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'TAG_ID');" ] ] } ``` -------------------------------- ### Firebase Deployment Command Source: https://vitepress.dev/guide/deploy Command to execute after building the project to deploy to Firebase. ```sh firebase deploy ``` -------------------------------- ### Firebase Hosting Configuration Source: https://vitepress.dev/guide/deploy Required configuration files for deploying to Firebase Hosting. ```json { "hosting": { "public": "docs/.vitepress/dist", "ignore": [] } } ``` ```json { "projects": { "default": "" } } ``` -------------------------------- ### Dynamic (Async) Config with Top-Level Await Source: https://vitepress.dev/reference/site-config Utilize top-level await within your configuration file to fetch data asynchronously before exporting the configuration object. This simplifies async operations in config files. ```javascript import { defineConfig } from 'vitepress' const posts = await (await fetch('https://my-cms.com/blog-posts')).json() export default defineConfig({ // app level config options lang: 'en-US', title: 'VitePress', description: 'Vite & Vue powered static site generator.', // theme level config options themeConfig: { sidebar: [ ...posts.map((post) => ({ text: post.name, link: `/posts/${post.name}` })) ] } }) ``` -------------------------------- ### Frontmatter Configuration for Prev/Next Links Source: https://vitepress.dev/reference/default-theme-prev-next-links Configuration options for customizing or disabling navigation links in the document footer. ```APIDOC ## Frontmatter Configuration ### Description Customize the text and link for the previous and next pages displayed at the bottom of documentation pages. These settings override the default behavior inferred from the sidebar configuration. ### Parameters #### Frontmatter Fields - **prev** (string | false | object) - Optional - Specifies the text/link for the previous page. Object structure: { text?: string; link?: string }. - **next** (string | false | object) - Optional - Specifies the text/link for the next page. Object structure: { text?: string; link?: string }. ### Request Example ```yaml --- prev: 'Get Started | Markdown' next: text: 'Markdown' link: '/guide/markdown' --- ``` ### Disabling Links To hide a navigation link, set the value to false: ```yaml --- prev: false --- ``` ``` -------------------------------- ### Dynamic route file structure Source: https://vitepress.dev/guide/routing Required file layout for dynamic routes, including the template file and the corresponding paths loader. ```text . └─ packages ├─ [pkg].md # route template └─ [pkg].paths.js # route paths loader ``` -------------------------------- ### Pass Raw Vite Configuration Source: https://vitepress.dev/reference/site-config Provide raw Vite configuration options to the internal Vite dev server or bundler. ```js export default { vite: { // Vite config options } } ``` -------------------------------- ### Configure Navigation Links Source: https://vitepress.dev/reference/default-theme-nav Add navigation links to the navbar by defining an array of objects for the `nav` option in `themeConfig`. Each object should have `text` and `link` properties. ```js export default { themeConfig: { nav: [ { text: 'Guide', link: '/guide' }, { text: 'Config', link: '/config' }, { text: 'Changelog', link: 'https://github.com/...' } ] } } ``` -------------------------------- ### Set Site Description Source: https://vitepress.dev/reference/site-config Configure the default site description, which is rendered as a meta tag. This can be overridden per page using frontmatter. ```ts export default { description: 'A VitePress site' } ``` -------------------------------- ### Create Basic Layout Component Source: https://vitepress.dev/guide/custom-theme A basic layout component must include the component to render markdown content. ```vue ``` -------------------------------- ### Navigation Menu Configuration Source: https://vitepress.dev/reference/default-theme-config Configure the navigation menu items, including links and dropdown menus. ```ts export default { themeConfig: { nav: [ { text: 'Guide', link: '/guide' }, { text: 'Dropdown Menu', items: [ { text: 'Item A', link: '/item-1' }, { text: 'Item B', link: '/item-2' }, { text: 'Item C', link: '/item-3' } ] } ] } } ``` -------------------------------- ### Define Project Root via CLI Source: https://vitepress.dev/guide/routing Specify a sub-directory as the project root when running VitePress commands. ```sh vitepress dev docs ``` -------------------------------- ### Reference Image in Public Directory Source: https://vitepress.dev/guide/asset-handling Assets placed in the `public` directory should be referenced using root absolute paths. These files are copied to the root of the output directory as-is. ```markdown ![An image](/image-inside-public.png) ``` -------------------------------- ### Define Theme Config with Types Source: https://vitepress.dev/guide/custom-theme Use `defineConfigWithTheme` and import theme-specific types to define your VitePress configuration, extending the base theme config. ```ts import baseConfig from 'awesome-vitepress-theme/config' import { defineConfigWithTheme } from 'vitepress' import type { ThemeConfig } from 'awesome-vitepress-theme' export default defineConfigWithTheme({ extends: baseConfig, themeConfig: { // Type is `ThemeConfig` } }) ``` -------------------------------- ### Implement Appearance Toggle Transitions Source: https://vitepress.dev/guide/extending-default-theme Extend the default theme to provide a custom View Transition when toggling between light and dark modes. ```vue ``` -------------------------------- ### Configure advanced markdown-it settings Source: https://vitepress.dev/guide/markdown Customize the markdown-it instance and plugins using the markdown configuration option. ```js import { defineConfig } from 'vitepress' import markdownItAnchor from 'markdown-it-anchor' import markdownItFoo from 'markdown-it-foo' export default defineConfig({ markdown: { // options for markdown-it-anchor // https://github.com/valeriangalliat/markdown-it-anchor#usage anchor: { permalink: markdownItAnchor.permalink.headerLink() }, // options for @mdit-vue/plugin-toc // https://github.com/mdit-vue/mdit-vue/tree/main/packages/plugin-toc#options toc: { level: [1, 2] }, config: (md) => { // use more markdown-it plugins! md.use(markdownItFoo) } } }) ``` -------------------------------- ### Configure Carbon Ads Source: https://vitepress.dev/reference/default-theme-config Set up Carbon Ads by providing your ad code, placement ID, and optionally the format. ```typescript export default { themeConfig: { carbonAds: { code: 'your-carbon-code', placement: 'your-carbon-placement' format: 'classic' } } } ``` ```typescript export interface CarbonAdsOptions { code: string placement: string format?: 'classic' | 'responsive' | 'cover' } ``` -------------------------------- ### Force Home Page Elements Source: https://vitepress.dev/reference/frontmatter-config Use the `isHome` frontmatter option to force the display of home page elements, even in a custom layout. ```yaml --- isHome: true --- ``` -------------------------------- ### Watch local files for updates Source: https://vitepress.dev/guide/data-loading Use the watch option with glob patterns to trigger hot updates when local files change. ```js import fs from 'node:fs' import { parse } from 'csv-parse/sync' export default { watch: ['./data/*.csv'], 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) => { return parse(fs.readFileSync(file, 'utf-8'), { columns: true, skip_empty_lines: true }) }) } } ``` -------------------------------- ### GitLab CI Configuration Source: https://vitepress.dev/guide/deploy Defines the build and deployment pipeline for GitLab Pages. ```yaml image: node:24 pages: cache: paths: - node_modules/ script: # - apk add git # Uncomment this if you're using small docker images like alpine and have lastUpdated enabled - npm install - npm run docs:build artifacts: paths: - public only: - main ``` -------------------------------- ### Enable image lazy loading Source: https://vitepress.dev/guide/markdown Configure the markdown image settings to enable lazy loading. ```js export default { markdown: { image: { // image lazy loading is disabled by default lazyLoading: true } } } ``` -------------------------------- ### Customize Prev Link Text Source: https://vitepress.dev/reference/default-theme-prev-next-links Use this frontmatter to change the text of the previous page link while keeping the default link. ```yaml --- prev: 'Get Started | Markdown' --- ``` -------------------------------- ### Configure tsconfig.json for VitePress IntelliSense Source: https://vitepress.dev/guide/using-vue Include `.md` files in the `include` pattern and add `.md` to `vueCompilerOptions.vitePressExtensions` in your `tsconfig.json` or `jsconfig.json` to enable VS Code IntelliSense for Markdown files. ```json { "include": [ "docs/**/*.ts", "docs/**/*.vue", "docs/**/*.md", ], "vueCompilerOptions": { "vitePressExtensions": [".md"], }, } ``` -------------------------------- ### Fetch and Format CMS Data for Dynamic Routes Source: https://vitepress.dev/guide/cms Fetch data from a CMS API and format it into paths data for VitePress dynamic routes. Use a CMS client library if necessary and include authentication tokens. ```javascript 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 } }) } } ``` -------------------------------- ### Basic Theme Configuration Source: https://vitepress.dev/reference/default-theme-config Define theme configuration via the `themeConfig` option in your VitePress config file. ```ts export default { lang: 'en-US', title: 'VitePress', description: 'Vite & Vue powered static site generator.', // Theme related configurations. themeConfig: { logo: '/logo.svg', nav: [...], sidebar: { ... } } } ``` -------------------------------- ### Enable Algolia Ask AI Source: https://vitepress.dev/reference/default-theme-search To include Algolia's Ask AI feature, pass the `askAi` option with your assistant ID within the search options. You can provide a simple string ID or an object for more granular control. ```typescript import { defineConfig } from 'vitepress' export default defineConfig({ themeConfig: { search: { provider: 'algolia', options: { appId: '...', apiKey: '...', indexName: '...', // askAi: "YOUR-ASSISTANT-ID" // OR askAi: { // at minimum you must provide the assistantId you received from Algolia assistantId: 'XXXYYY', // optional overrides – if omitted, the top-level appId/apiKey/indexName values are reused // apiKey: '...', // appId: '...', // indexName: '...' } } } } }) ```