### Initialize VitePress Project Source: https://vitepress.dev/guide/getting-started Run the setup wizard to scaffold a basic project structure. ```sh $ npx vitepress init ``` ```sh $ pnpm vitepress init ``` ```sh $ yarn vitepress init ``` ```sh $ bun vitepress init ``` -------------------------------- ### Install CSS Pre-processors Source: https://vitepress.dev/guide/using-vue Install the required pre-processor package before using it in Markdown or components. ```bash # .scss and .sass npm install -D sass # .less npm install -D less # .styl and .stylus npm install -D stylus ``` -------------------------------- ### Install MathJax dependency Source: https://vitepress.dev/guide/markdown Install the required markdown-it-mathjax3 package as a development dependency. ```sh npm add -D markdown-it-mathjax3@^4 ``` -------------------------------- ### Start development server via npm scripts Source: https://vitepress.dev/guide/getting-started Run the development server using the configured npm scripts. ```sh $ npm run docs:dev ``` ```sh $ pnpm run docs:dev ``` ```sh $ yarn run 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 ``` ```sh $ deno add -D vitepress@next ``` -------------------------------- ### Importing Vue components in Markdown Source: https://vitepress.dev/guide/using-vue Use script setup blocks to import components locally for better code splitting. ```md # Docs This is a .md using a custom component ## More docs ... ``` -------------------------------- ### Define script and style in Markdown Source: https://vitepress.dev/guide/using-vue Integrates script setup and module styles into a Markdown file, noting that all content outside tags is treated as Markdown. ```html --- hello: world --- ## Markdown Content The count is: {{ count }} ``` -------------------------------- ### VitePress Project File Structure Source: https://vitepress.dev/guide/getting-started Visual representation of the recommended directory layout when installing VitePress in a nested directory. ```text . ├─ docs │ ├─ .vitepress │ │ └─ config.js │ ├─ api-examples.md │ ├─ markdown-examples.md │ └─ index.md └─ package.json ``` -------------------------------- ### Example output of page metadata Source: https://vitepress.dev/guide/using-vue Represents the JSON structure returned by the page metadata helper. ```json { "path": "/using-vue.html", "title": "Using Vue in Markdown", "frontmatter": {}, ... } ``` -------------------------------- ### Define Internal Links Source: https://vitepress.dev/guide/markdown Examples of various internal link formats supported by VitePress for SPA navigation. ```markdown [Home](/) [foo](/foo/) [foo heading](./#heading) [bar - three](../bar/three) [bar - three](../bar/three.md) [bar - four](../bar/four.html) ``` -------------------------------- ### 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 ``` -------------------------------- ### Create Task Lists Source: https://vitepress.dev/guide/markdown Use brackets to create interactive-looking task lists. ```md - [ ] Write the press release - [x] Update the website ``` -------------------------------- ### Deploy to Firebase Source: https://vitepress.dev/guide/deploy Execute the deployment command after building the project. ```sh firebase deploy ``` -------------------------------- ### Define Custom Containers Source: https://vitepress.dev/guide/markdown Use the ::: syntax to create various types of info boxes and details blocks. ```md ::: 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. ::: ``` -------------------------------- ### Override line number settings in code blocks Source: https://vitepress.dev/guide/markdown Use :line-numbers or :no-line-numbers in the code block fence to override global settings, or use :line-numbers=n to set a starting index. ```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' ``` ``` -------------------------------- ### Deploy to Surge Source: https://vitepress.dev/guide/deploy Deploy the built static files to Surge. ```sh npx surge docs/.vitepress/dist ``` -------------------------------- ### Configure Netlify _headers File Source: https://vitepress.dev/guide/deploy Place this file in the public directory to apply cache headers on Netlify deployments. ```text /assets/* cache-control: max-age=31536000 cache-control: immutable ``` -------------------------------- ### Configure Netlify Redirects Source: https://vitepress.dev/guide/i18n Redirect users to language-specific directories based on browser language settings. ```text /* /es/:splat 302 Language=es /* /fr/:splat 302 Language=fr /* /en/:splat 302 ``` -------------------------------- ### Configure GitHub Actions for VitePress Source: https://vitepress.dev/guide/deploy Create this workflow file in .github/workflows/deploy.yml to automate building and deploying to GitHub Pages. ```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: Cache VitePress uses: actions/cache@v4 with: path: docs/.vitepress/cache key: ${{ runner.os }}-vitepress-${{ hashFiles('docs/**', 'package-lock.json', 'pnpm-lock.yaml', 'yarn.lock', 'bun.lockb') }} restore-keys: | ${{ runner.os }}-vitepress- - 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 dynamic rewrites with parameters Source: https://vitepress.dev/guide/routing Uses path-to-regexp syntax to define dynamic route patterns for cleaner configuration in projects with repetitive structures. ```ts export default { rewrites: { 'packages/:pkg/src/:slug*': ':pkg/:slug*' } } ``` -------------------------------- ### Define relative links with rewrites Source: https://vitepress.dev/guide/routing Demonstrates how to construct relative links based on the final rewritten paths rather than the source file structure. ```md [Link to PKG B](../pkg-b/pkg-b-code) ``` -------------------------------- ### Configure tsconfig.json for Markdown support Source: https://vitepress.dev/guide/using-vue Include .md files in the project configuration and register them in the vueCompilerOptions. ```json { "include": [ "docs/**/*.ts", "docs/**/*.vue", "docs/**/*.md", ], "vueCompilerOptions": { "vitePressExtensions": [".md"], }, } ``` -------------------------------- ### Configure GitLab CI for VitePress Source: https://vitepress.dev/guide/deploy Create a .gitlab-ci.yml file in the project root to automate deployment to 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 ``` -------------------------------- ### Configure Build and Preview Scripts Source: https://vitepress.dev/guide/deploy Define the build and preview scripts in your package.json to manage the VitePress site located in the docs directory. ```json { "scripts": { "docs:build": "vitepress build docs", "docs:preview": "vitepress preview docs" } } ``` -------------------------------- ### Create a basic layout component Source: https://vitepress.dev/guide/custom-theme A minimal layout component must include the component to render markdown content. ```vue ``` -------------------------------- ### Create GitHub-Style Tables Source: https://vitepress.dev/guide/markdown Define tables using pipes and hyphens for alignment. ```md | Tables | Are | Cool | | ------------- | :-----------: | ----: | | col 3 is | right-aligned | $1600 | | col 2 is | centered | $12 | | zebra stripes | are neat | $1 | ``` -------------------------------- ### Configure Nginx Server Block Source: https://vitepress.dev/guide/deploy Set up Nginx to serve static files with gzip compression, caching headers, and clean URL support. ```nginx server { gzip on; gzip_types text/plain text/css application/json application/javascript text/xml application/xml application/xml+rss text/javascript; listen 80; server_name _; index index.html; location / { # content location root /app; # exact matches -> reverse clean urls -> folders -> not found try_files $uri $uri.html $uri/ =404; # non existent pages error_page 404 /404.html; # a folder without index.html raises 403 in this setup error_page 403 /404.html; # adjust caching headers # files in the assets folder have hashes filenames location ~* ^/assets/ { expires 1y; add_header Cache-Control "public, immutable"; } } } ``` -------------------------------- ### Configure content loader options Source: https://vitepress.dev/guide/data-loading Customize the loader to include source, HTML, or excerpts, and transform the data before it is shipped to the client. ```js import { createContentLoader } from 'vitepress' export default createContentLoader('posts/*.md', { includeSrc: true, // include raw markdown source? render: true, // include rendered full page HTML? excerpt: true, // include excerpt? transform(rawData) { // map, sort, or filter the raw data as you wish. // the final result is what will be shipped to the client. return rawData.sort((a, b) => { return +new Date(b.frontmatter.date) - +new Date(a.frontmatter.date) }).map((page) => { page.src // raw markdown source page.html // rendered full page HTML page.excerpt // rendered excerpt HTML (content above first `---`) return {/* ... */} }) } }) ``` -------------------------------- ### Configure Preview Port Source: https://vitepress.dev/guide/deploy Customize the local preview server port by modifying the preview script argument. ```json { "scripts": { "docs:preview": "vitepress preview docs --port 8080" } } ``` -------------------------------- ### Importing Code Snippets Source: https://vitepress.dev/guide/markdown Use the <<< syntax to import code from files. The @ symbol refers to the source root. ```md <<< @/filepath ``` ```md <<< @/filepath{highlightLines} ``` ```md <<< @/snippets/snippet.js{2} ``` ```md <<< ../snippets/snippet.js ``` -------------------------------- ### Use withBase for dynamic asset paths Source: https://vitepress.dev/guide/asset-handling Wrap dynamic paths with the withBase helper to ensure compatibility with the base configuration. ```vue ``` -------------------------------- ### 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 } } ``` -------------------------------- ### Configure Firebase Hosting Source: https://vitepress.dev/guide/deploy Define the public directory and project ID for Firebase deployment. ```json { "hosting": { "public": "docs/.vitepress/dist", "ignore": [] } } ``` ```json { "projects": { "default": "" } } ``` -------------------------------- ### Enable Sitemap Generation Source: https://vitepress.dev/guide/sitemap-generation Basic configuration to enable sitemap generation by specifying the site hostname. ```ts export default { sitemap: { hostname: 'https://example.com' } } ``` -------------------------------- ### Define a basic data loader Source: https://vitepress.dev/guide/data-loading Create a file ending in .data.js or .data.ts with a default export containing a load() method. ```js export default { load() { return { hello: 'world' } } } ``` -------------------------------- ### Configure VitePress Site Settings Source: https://vitepress.dev/guide/getting-started Basic configuration structure for defining site title, description, and theme options in the config file. ```js export default { // site-level options title: 'VitePress', description: 'Just playing around.', themeConfig: { // theme-level options } } ``` -------------------------------- ### Apply theme configuration types Source: https://vitepress.dev/guide/custom-theme Use this pattern to enable TypeScript support for theme-specific configuration options. ```ts import baseConfig from 'awesome-vitepress-theme/config' import { defineConfig } from 'vitepress' import type { ThemeConfig } from 'awesome-vitepress-theme' export default defineConfig({ extends: baseConfig, themeConfig: { // Type is `ThemeConfig` } }) ``` -------------------------------- ### Defining Paths with Content Source: https://vitepress.dev/guide/routing Pass raw content to pages by including a content property in the paths object returned by the configuration. ```js export default { async paths() { const posts = await (await fetch('https://my-cms.com/blog-posts')).json() return posts.map((post) => { return { params: { id: post.id }, content: post.content // raw Markdown or HTML } }) } } ``` -------------------------------- ### Use Teleports with ClientOnly Source: https://vitepress.dev/guide/using-vue Wrap Teleport components in ClientOnly to ensure compatibility with SSG. ```markdown
// ...
``` -------------------------------- ### Configure package.json scripts Source: https://vitepress.dev/guide/getting-started Add these scripts to your package.json to enable VitePress development, build, and preview commands. ```json { ... "scripts": { "docs:dev": "vitepress dev docs", "docs:build": "vitepress build docs", "docs:preview": "vitepress preview docs" }, ... } ``` -------------------------------- ### Create a content loader Source: https://vitepress.dev/guide/data-loading Use this to export a data loader object for a collection of Markdown files. ```js import { createContentLoader } from 'vitepress' export default createContentLoader('posts/*.md', /* options */) ``` -------------------------------- ### createContentLoader(pattern, options) Source: https://vitepress.dev/guide/data-loading Creates a data loader object for a collection of Markdown files. It returns a loader that can be used as a default export in data loader files or invoked manually in build hooks. ```APIDOC ## createContentLoader(pattern, options) ### Description Creates a content loader that matches Markdown files based on a glob pattern. It returns an object with `watch` and `load` methods, allowing for efficient data collection and transformation. ### Parameters - **pattern** (string) - Required - A glob pattern relative to the source directory. - **options** (ContentOptions) - Optional - Configuration object to control data inclusion and transformation. ### Options - **includeSrc** (boolean) - Optional - Whether to include the raw markdown source. Default: false. - **render** (boolean) - Optional - Whether to render the source to HTML and include it in the data. Default: false. - **excerpt** (boolean | function | string) - Optional - Whether to parse and include the excerpt. Can be a boolean, a custom extraction function, or a separator string. Default: false. - **transform** (function) - Optional - A function to map, sort, or filter the raw data before it is shipped to the client. ### Return Value - **loader** (object) - An object containing `watch` and `load` methods, where `load()` returns a Promise resolving to an array of `ContentData` objects. ``` -------------------------------- ### 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 ``` -------------------------------- ### Configure Sitemap with Base Path Source: https://vitepress.dev/guide/sitemap-generation Ensure the hostname includes the base path when the site is deployed to a sub-directory. ```ts export default { base: '/my-site/', sitemap: { hostname: 'https://example.com/my-site/' } } ``` -------------------------------- ### ContentOptions interface Source: https://vitepress.dev/guide/data-loading Configuration options for the createContentLoader function. ```ts interface ContentOptions { /** * Include src? * @default false */ includeSrc?: boolean /** * Render src to HTML and include in data? * @default false */ render?: boolean /** * If `boolean`, whether to parse and include excerpt? (rendered as HTML) * * If `function`, control how the excerpt is extracted from the content. * * If `string`, define a custom separator to be used for extracting the * excerpt. Default separator is `---` if `excerpt` is `true`. * * @see https://github.com/jonschlinkert/gray-matter#optionsexcerpt * @see https://github.com/jonschlinkert/gray-matter#optionsexcerpt_separator * * @default false */ excerpt?: | boolean | ((file: { data: { [key: string]: any }; content: string; excerpt?: string }, options?: any) => void) | string /** * Transform the data. Note the data will be inlined as JSON in the client * bundle if imported from components or markdown files. */ transform?: (data: ContentData[]) => T | Promise } ``` -------------------------------- ### Represent Directory Structure Source: https://vitepress.dev/guide/markdown Visual representation of a project directory structure for documentation purposes. ```text . ├─ index.md ├─ foo │ ├─ index.md │ ├─ one.md │ └─ two.md └─ bar ├─ index.md ├─ three.md └─ four.md ``` -------------------------------- ### Dynamically Generate Paths Source: https://vitepress.dev/guide/routing Paths can be generated dynamically at build time using local file system access or remote API requests. ```js import fs from 'node:fs' export default { paths() { return fs .readdirSync('packages') .map((pkg) => { return { params: { pkg }} }) } } ``` ```js export default { async paths() { const pkgs = await (await fetch('https://my-api.com/packages')).json() return pkgs.map((pkg) => { return { params: { pkg: pkg.name, version: pkg.version } } }) } } ``` -------------------------------- ### Configure Cache-Control Header Source: https://vitepress.dev/guide/deploy Apply this header to files within the assets directory to enable long-term caching. ```text Cache-Control: max-age=31536000,immutable ``` -------------------------------- ### Bind an image source dynamically Source: https://vitepress.dev/guide/asset-handling Directly binding a path to an image source without the withBase helper. ```vue ``` -------------------------------- ### Link to pages using relative or absolute paths Source: https://vitepress.dev/guide/routing Use paths without file extensions to allow VitePress to generate correct URLs based on configuration. ```markdown [Getting Started](./getting-started) [Getting Started](../guide/getting-started) [Getting Started](./getting-started.md) [Getting Started](./getting-started.html) ``` -------------------------------- ### Invoke VitePress directly Source: https://vitepress.dev/guide/getting-started Run the VitePress development server directly without using npm scripts. ```sh $ npx vitepress dev docs ``` ```sh $ pnpm vitepress dev docs ``` ```sh $ yarn vitepress dev docs ``` ```sh $ bun vitepress dev docs ``` -------------------------------- ### Fetch and format CMS data for dynamic routes Source: https://vitepress.dev/guide/cms Implement the paths export to fetch external data and map it to the required params and content structure. ```js export default { async paths() { // use respective CMS client library if needed const data = await (await fetch('https://my-cms-api', { headers: { // token if necessary } })).json() return data.map(entry => { return { params: { id: entry.id, /* title, authors, date etc. */ }, content: entry.content } }) } } ``` -------------------------------- ### Creating Code Groups Source: https://vitepress.dev/guide/markdown Use the ::: code-group container to organize multiple code blocks into tabs. ```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] ::: ``` -------------------------------- ### Define JSON Frontmatter Source: https://vitepress.dev/guide/frontmatter Use JSON syntax enclosed in curly braces between triple-dashed lines as an alternative to YAML. ```json --- { "title": "Blogging Like a Hacker", "editLink": true } --- ``` -------------------------------- ### Configure MathJax in VitePress Source: https://vitepress.dev/guide/markdown Enable math rendering by setting the math property to true within the markdown configuration object. ```ts export default { markdown: { math: true } } ``` -------------------------------- ### Configure Vercel Headers in vercel.json Source: https://vitepress.dev/guide/deploy Define header rules in the project root to manage caching for assets on Vercel. ```json { "headers": [ { "source": "/assets/(.*)", "headers": [ { "key": "Cache-Control", "value": "max-age=31536000, immutable" } ] } ] } ``` -------------------------------- ### Importing Code with Regions and Language Specification Source: https://vitepress.dev/guide/markdown Specify regions using # and override language inference using curly braces. ```md <<< @/snippets/snippet-with-region.js#snippet{1} ``` ```md <<< @/snippets/snippet.cs{c#} ``` ```md <<< @/snippets/snippet.cs{1,2,4-6 c#} ``` ```md <<< @/snippets/snippet.cs{1,2,4-6 c#:line-numbers} ``` -------------------------------- ### Use Vue interpolation in Markdown Source: https://vitepress.dev/guide/using-vue Demonstrates basic Vue-style interpolation within Markdown text. ```md {{ 1 + 1 }} ``` -------------------------------- ### Watch Template and Data Files Source: https://vitepress.dev/guide/routing Use the watch option to trigger page regeneration during development when specific files change. ```js // posts/[slug].paths.js import fs from 'node:fs' import { renderTemplate } from './templates/renderer.js' export default { // Watch for changes to template files and data sources watch: [ './templates/**/*.njk', // Template files '../data/**/*.json' // Data files ], paths(watchedFiles) { // watchedFiles will be an array of absolute paths of the matched files // Read data files to generate routes const dataFiles = watchedFiles.filter(file => file.endsWith('.json')) return dataFiles.map(file => { const data = JSON.parse(fs.readFileSync(file, 'utf-8')) return { params: { slug: data.slug }, content: renderTemplate(data) // Use template to generate content } }) } } ``` -------------------------------- ### Define Theme Entry File Structure Source: https://vitepress.dev/guide/custom-theme The directory structure for a VitePress project with a custom theme entry file. ```text . ├─ docs # project root │ ├─ .vitepress │ │ ├─ theme │ │ │ └─ index.js # theme entry │ └─ config.js # config file └─ index.md └─ package.json ``` -------------------------------- ### Access Site Configuration Source: https://vitepress.dev/guide/data-loading Retrieve the VitePress site configuration object using the global VITEPRESS_CONFIG property. ```ts import type { SiteConfig } from 'vitepress' const config: SiteConfig = (globalThis as any).VITEPRESS_CONFIG ``` -------------------------------- ### Directory structure for clean URLs Source: https://vitepress.dev/guide/routing Organize files using index.md files within directories to support clean URLs without server-side configuration. ```text . ├─ getting-started │ └─ index.md ├─ installation │ └─ index.md └─ index.md ``` -------------------------------- ### Load and Parse CSV Files Source: https://vitepress.dev/guide/data-loading Uses the watch option with glob patterns to monitor CSV files and parse them into JSON during the build process. ```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 }) }) } } ``` -------------------------------- ### Reference an asset in the public directory Source: https://vitepress.dev/guide/asset-handling Reference files located in the public directory using a root absolute path. ```md ![An image](/image-inside-public.png) ``` -------------------------------- ### Customize Markdown-it Instance Source: https://vitepress.dev/guide/markdown Use the config function within the markdown configuration to register custom markdown-it plugins or modify the renderer instance. ```js import { defineConfig } from 'vitepress' import { headerLink } from '@mdit/plugin-anchor' import markdownItFoo from 'markdown-it-foo' export default defineConfig({ markdown: { // options for @mdit/plugin-anchor // https://mdit-plugins.github.io/anchor.html anchor: { 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) } } }) ``` -------------------------------- ### Implement View Transitions for Appearance Toggle Source: https://vitepress.dev/guide/extending-default-theme Uses the View Transitions API to create a circular reveal animation when toggling between light and dark modes. Requires browser support for startViewTransition and user preference for motion. ```vue ``` -------------------------------- ### Register New Custom Containers Source: https://vitepress.dev/guide/markdown Define additional container types in the configuration and apply custom CSS for styling. ```ts // config.ts export default defineConfig({ // ... markdown: { container: { customContainers: { success: 'SUCCESS' } } } // ... }) ``` ```md ::: success You have completed the walkthrough! ::: > [!SUCCESS] Custom title > This renders the same way. ``` ```css /* .vitepress/theme/custom.css */ .custom-block.success { border-color: transparent; color: var(--vp-c-text-1); background-color: var(--vp-c-success-soft); } ``` -------------------------------- ### Configure rewrites using a function Source: https://vitepress.dev/guide/routing Provides a functional approach to path transformation by receiving the original path and returning the new one. ```ts export default { rewrites(id) { return id.replace(/^packages\/([^/]+)\/src\//, '$1/') } } ``` -------------------------------- ### Apply Attributes to Containers Source: https://vitepress.dev/guide/markdown Use curly braces to add attributes like 'open' or 'no-title' to containers. ```md ::: details Click me to toggle the code {open} ```js console.log('Hello, VitePress!') ``` ::: ``` ```md ::: tip {no-title} Just want to try it out? Skip to the [Quickstart](./getting-started). ::: ``` -------------------------------- ### Configure Heroku Static Buildpack Source: https://vitepress.dev/guide/deploy Specify the root directory for the static buildpack in Heroku. ```json { "root": "docs/.vitepress/dist" } ``` -------------------------------- ### Configure Custom Container Titles Source: https://vitepress.dev/guide/markdown Add custom titles to containers or configure global labels in the site configuration. ```md ::: danger STOP Danger zone, do not proceed ::: ::: details Click me to toggle the code ```js console.log('Hello, VitePress!') ``` ::: ``` ```ts // config.ts export default defineConfig({ // ... markdown: { container: { tipLabel: '提示', warningLabel: '警告', dangerLabel: '危险', infoLabel: '信息', detailsLabel: '详细信息' } } // ... }) ``` -------------------------------- ### Define YAML Frontmatter Source: https://vitepress.dev/guide/markdown Use YAML blocks at the top of a file to define page metadata like title and language. ```yaml --- title: Blogging Like a Hacker lang: en-US --- ``` -------------------------------- ### Use CSS Pre-processors in Components Source: https://vitepress.dev/guide/using-vue Specify the language attribute in the style tag to use pre-processor syntax. ```vue ``` -------------------------------- ### GitHub-flavored Alerts Syntax Source: https://vitepress.dev/guide/markdown Use blockquotes with specific markers to create callouts. Text immediately following the marker serves as the alert title. ```markdown > [!NOTE] > Highlights information that users should take into account, even when skimming. > [!TIP] > Optional information to help a user be more successful. > [!IMPORTANT] > Crucial information necessary for users to succeed. > [!WARNING] > Critical content demanding immediate user attention due to potential risks. > [!CAUTION] > Negative potential consequences of an action. ``` -------------------------------- ### Add Footnotes Source: https://vitepress.dev/guide/markdown Include standard and inline footnotes using bracket syntax. ```md Footnotes are supported[^1], including inline ones^[This is an inline footnote.]. [^1]: Definitions can contain **markdown** and are rendered at the end of the page. ``` -------------------------------- ### Extend theme base configuration Source: https://vitepress.dev/guide/custom-theme Use this pattern in your VitePress config file if the theme provides a specific configuration sub-path. ```ts import baseConfig from 'awesome-vitepress-theme/config' export default { // extend theme base config (if needed) extends: baseConfig } ``` -------------------------------- ### Import and re-export a custom theme Source: https://vitepress.dev/guide/custom-theme Use this pattern to consume an external theme directly in your theme entry file. ```js import Theme from 'awesome-vitepress-theme' export default Theme ``` -------------------------------- ### Markdown Math Syntax Source: https://vitepress.dev/guide/markdown Use LaTeX syntax for inline and block mathematical equations in Markdown files. ```md When $a \ne 0$, there are two solutions to $(ax^2 + bx + c = 0)$ and they are $$ x = {-b \pm \sqrt{b^2-4ac} \over 2a} $$ ``` -------------------------------- ### Define Multiple Route Params Source: https://vitepress.dev/guide/routing Dynamic routes can include multiple parameters to generate complex URL structures. ```js export default { paths: () => [ { params: { pkg: 'foo', version: '1.0.0' }}, { params: { pkg: 'foo', version: '2.0.0' }}, { params: { pkg: 'bar', version: '1.0.0' }}, { params: { pkg: 'bar', version: '2.0.0' }} ] } ``` -------------------------------- ### Configure static rewrites in VitePress Source: https://vitepress.dev/guide/routing Maps specific source files to desired output paths using the rewrites object in the configuration file. ```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' } } ``` -------------------------------- ### Preload local font files using transformHead Source: https://vitepress.dev/guide/extending-default-theme Use the transformHead build hook to preload local font files processed as assets. ```js export default { transformHead({ assets }) { // adjust the regex accordingly to match your font const myFontFile = assets.find(file => /font-name\.[\w-]+\.woff2/.test(file)) if (myFontFile) { return [ [ 'link', { rel: 'preload', href: myFontFile, as: 'font', type: 'font/woff2', crossorigin: '' } ] ] } } } ``` -------------------------------- ### Render CMS content in Markdown Source: https://vitepress.dev/guide/cms Access the dynamic route parameters and inject the CMS content using the @content placeholder. ```md # {{ $params.title }} - by {{ $params.author }} on {{ $params.date }} ``` -------------------------------- ### Configure VS Code settings for Markdown Source: https://vitepress.dev/guide/using-vue Add markdown to the vue.server.includeLanguages setting to ensure the Vue language server processes Markdown files. ```json { "vue.server.includeLanguages": ["vue", "markdown"] } ``` -------------------------------- ### Apply colored diffs to code blocks Source: https://vitepress.dev/guide/markdown Use // [!code --] or // [!code ++] comments to highlight removed or added lines while maintaining syntax highlighting. ```js export default { data () { return { msg: 'Removed' // [!!code --] msg: 'Added' // [!!code ++] } } } ``` ```js export default { data () { return { msg: 'Removed' // [!code --] msg: 'Added' // [!code ++] } } } ``` -------------------------------- ### Register Global Components Source: https://vitepress.dev/guide/extending-default-theme Register custom components globally within the theme configuration using the enhanceApp hook. ```js import DefaultTheme from 'vitepress/theme' /** @type {import('vitepress').Theme} */ export default { extends: DefaultTheme, enhanceApp({ app }) { // register your custom global components app.component('MyGlobalComponent' /* ... */) } } ``` ```ts import type { Theme } from 'vitepress' import DefaultTheme from 'vitepress/theme' export default { extends: DefaultTheme, enhanceApp({ app }) { // register your custom global components app.component('MyGlobalComponent' /* ... */) } } satisfies Theme ``` -------------------------------- ### Define an async data loader Source: https://vitepress.dev/guide/data-loading The load() method can be asynchronous to fetch remote data during the build. ```js export default { async load() { // fetch remote data return (await fetch('...')).json() } } ``` -------------------------------- ### Include a relative markdown file Source: https://vitepress.dev/guide/markdown Use the include syntax to pull content from a separate markdown file into the current document. ```md # Docs ## Basics ``` ```md Some getting started stuff. ### Configuration Can be created using `.foorc.json`. ``` ```md # Docs ## Basics Some getting started stuff. ### Configuration Can be created using `.foorc.json`. ``` -------------------------------- ### Load environment variables for CMS authentication Source: https://vitepress.dev/guide/cms Use loadEnv to access API tokens from an .env file within a dynamic route path file. ```js // posts/[id].paths.js import { loadEnv } from 'vitepress' const env = loadEnv('', process.cwd()) ``` -------------------------------- ### Type-safe Loader with defineRoutes Source: https://vitepress.dev/guide/routing Use defineRoutes in TypeScript to enable type hints for hooks like paths, watch, and transformPageData. ```ts // packages/[pkg].paths.ts import { defineRoutes } from 'vitepress' export default defineRoutes({ watch: ['../data/**/*.json'], async paths() { return [ { params: { pkg: 'foo' } }, { params: { pkg: 'bar' } } ] }, async transformPageData(pageData) { pageData.title = `${pageData.title} · Packages` } }) ``` -------------------------------- ### Rendering Raw Content Source: https://vitepress.dev/guide/routing Use the special comment syntax to inject the content property into the rendered Markdown. ```md ``` -------------------------------- ### Conditionally import dependencies using SSR flag Source: https://vitepress.dev/guide/ssr-compat Use the import.meta.env.SSR flag to conditionally load browser-dependent code or plugins. ```js if (!import.meta.env.SSR) { import('./lib-that-access-window-on-import').then((module) => { // use code }) } ``` ```js /** @type {import('vitepress').Theme} */ export default { // ... async enhanceApp({ app }) { if (!import.meta.env.SSR) { const plugin = await import('plugin-that-access-window-on-import') app.use(plugin.default) } } } ``` ```ts import type { Theme } from 'vitepress' export default { // ... async enhanceApp({ app }) { if (!import.meta.env.SSR) { const plugin = await import('plugin-that-access-window-on-import') app.use(plugin.default) } } } satisfies Theme ``` -------------------------------- ### Define Locale Configuration Source: https://vitepress.dev/guide/i18n Configure multiple languages in the VitePress configuration file using the locales property. ```ts import { defineConfig } from 'vitepress' export default defineConfig({ // shared properties and other top-level stuff... locales: { root: { label: 'English', lang: 'en' }, fr: { label: 'French', lang: 'fr', // optional, will be added as `lang` attribute on `html` tag link: '/fr/guide' // default /fr/ -- shows on navbar translations menu, can be external // other locale specific properties... } } }) ``` -------------------------------- ### Syntax Highlighting in Code Blocks Source: https://vitepress.dev/guide/markdown Append a language alias to the opening backticks of a code block to enable Shiki syntax highlighting. ```markdown ```js export default { name: 'MyComponent', // ... } ``` ``` ```markdown ```html
  • {{ todo.text }}
``` ``` -------------------------------- ### Use Emoji Shortcodes Source: https://vitepress.dev/guide/markdown Insert emojis using colon-delimited shortcodes. ```text :tada: :100: ``` -------------------------------- ### Include a specific line range Source: https://vitepress.dev/guide/markdown Specify a line range in curly braces after the file path to include only a portion of the file. ```md # Docs ## Basics ``` ```md Some getting started stuff. ### Configuration Can be created using `.foorc.json`. ``` ```md # Docs ## Basics ### Configuration Can be created using `.foorc.json`. ``` -------------------------------- ### Generate Table of Contents Source: https://vitepress.dev/guide/markdown Use the [[toc]] syntax to automatically generate a table of contents in your Markdown files. ```markdown [[toc]] ``` -------------------------------- ### Import data in components Source: https://vitepress.dev/guide/data-loading Access the loaded data in .md or .vue files using the named export 'data'. ```vue
{{ data }}
``` -------------------------------- ### Enable Image Lazy Loading Source: https://vitepress.dev/guide/markdown Set lazyLoad to true within the markdown configuration object to enable lazy loading for images. ```js export default { markdown: { image: { // image lazy loading is disabled by default lazyLoad: true } } } ``` -------------------------------- ### Define Basic Paths Loader Source: https://vitepress.dev/guide/routing The paths loader must export a default object with a paths method that returns an array of objects containing params. ```js // packages/[pkg].paths.js export default { paths() { return [ { params: { pkg: 'foo' }}, { params: { pkg: 'bar' }} ] } } ``` -------------------------------- ### Use content loader in build hooks Source: https://vitepress.dev/guide/data-loading Invoke the loader manually within build hooks like buildEnd to generate auxiliary files. ```js export default { async buildEnd() { const posts = await createContentLoader('posts/*.md').load() // generate files based on posts metadata, e.g. RSS feed } } ``` -------------------------------- ### Wrap non-SSR-friendly components with ClientOnly Source: https://vitepress.dev/guide/ssr-compat Use the ClientOnly component to prevent non-SSR-friendly components from executing during the server-side build. ```md ``` -------------------------------- ### Highlighting specific lines in code blocks Source: https://vitepress.dev/guide/markdown Use curly brace syntax after the language identifier to highlight specific lines, ranges, or a combination of both. ```js export default { data () { return { msg: 'Highlighted!' } } } ``` ```js 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', } } } ``` -------------------------------- ### Define YAML Frontmatter Source: https://vitepress.dev/guide/frontmatter Place YAML metadata between triple-dashed lines at the very top of a Markdown file. ```md --- title: Docs with VitePress editLink: true --- ``` -------------------------------- ### Configure global line numbers Source: https://vitepress.dev/guide/markdown Enable line numbers globally by setting the markdown.lineNumbers option in the VitePress configuration. ```js export default { markdown: { lineNumbers: true } } ```