VitePress Documentation

website·Indexed 32 days ago

https://vitepress-swiper.cssnr.com

A static site generator that allows for custom themes and built-in components like Badge for adding status labels to headers.

Tokens
3K
Snippets
14
Records
16
Agent score
50%

What's inside VitePress

  1. Build a custom layout component

    A basic layout must include the <Content /> component to render markdown content. You can use the useData() helper to access page.isNotFound for 404 pages or frontmatter to conditionally render different layouts based on page-level configuration (e.g., layout: home).
    <script setup>
    import { useData } from 'vitepress'
    const { page, frontmatter } = useData()
    </script>
    
    <template>
      <h1 >Custom Layout!</h1>
    
      <div v-if="page.isNotFound">
        Custom 404 page!
      </div>
      <div v-if="frontmatter.layout === 'home'">
        Custom home page!
      </div>
      <Content v-else />
    </template>
  2. Generate image URLs dynamically in <VPSwiper>

    If images are named numerically and ordered sequentially, you can use dynamic URL generation to reduce boilerplate. The plugin constructs URLs using the pattern: base-url + / + file-name-prefix + file# + file-ext.

    This requires the use of base-url instead of :slides.

    <VPSwiper
      base-url="https://example.com/path"
      :number-of-slides="4"
      :start-at="8"
      :pad-start="2"
      file-name-prefix="slide-"
      file-ext=".png"
      :pagination="{ clickable: true }"
      :grab-cursor="false"
      margin-top="40px"
      effect="fade"
    />

    // Resulting URLs: // https://example.com/path/slide-08.png // https://example.com/path/slide-09.png // https://example.com/path/slide-10.png // https://example.com/path/slide-11.png

  3. Implement the VitePress Theme interface

    A custom theme is defined as an object exported as the default export from the theme entry file. The only required property is Layout. Optional hooks include enhanceApp for Vue app instance modification, setup for Composition API logic in the root component, and extends to inherit from another theme.
    interface Theme {
      /** Root layout component for every page @required */
      Layout: Component
      /** Enhance Vue app instance @optional */
      enhanceApp?: (ctx: EnhanceAppContext) => Awaitable<void>
      /** Runs inside the root component's `setup()` @optional */
      setup?: () => void
      /** Extend another theme @optional */
      extends?: Theme
    }
    
    interface EnhanceAppContext {
      app: App // Vue app instance
      router: Router // VitePress router instance
      siteData: Ref<SiteData> // Site-level metadata
    }
  4. Use the setup hook for Composition API logic

    The setup hook runs inside the root component's setup(), allowing the use of Composition API calls (like watch or onMounted) without wrapping them in a layout component. Note that browser-only work must be placed inside onMounted as this hook also runs during SSR/SSG.
    import { watch } from 'vue'
    import { useData } from 'vitepress'
    import DefaultTheme from 'vitepress/theme'
    
    export default {
      extends: DefaultTheme,
      setup() {
        const { page } = useData()
        watch(() => page.value.relativePath, (path) => {
          console.log('now viewing', path)
        })
      }
    }
  5. Use the Badge component in VitePress

    The Badge component is globally available in VitePress and is used to add status labels (such as version numbers or status tags) to headers. It can be used by providing a text prop or by passing children into the component slot.
    ### Title <Badge type="info" text="default" />
    ### Title <Badge type="tip" text="^1.9.0" />
    ### Title <Badge type="warning" text="beta" />
    ### Title <Badge type="danger" text="deprecated" />
    
    <!-- Using custom children instead of the text prop -->
    ### Title <Badge type="info">custom element</Badge>
  6. Install VPSwiper from source for full control

    If you need full control over the template, you can manually add the source file to your project. Note that this method is manual and does not provide automatic updates.

    1. Copy VPSwiper.vue from the official repository to .vitepress/theme/components/VPSwiper.vue.
    2. Install the swiper dependency via your preferred package manager.
    3. Register the local component in your .vitepress/theme/index.ts file.
    # Install dependency
    npm i swiper # or pnpm i swiper / yarn add swiper / bun i swiper
    // .vitepress/theme/index.ts
    import DefaultTheme, { VPBadge } from 'vitepress/theme'
    import VPSwiper from './components/VPSwiper.vue'
    
    export default {
      ...DefaultTheme,
      enhanceApp({ app }) {
        app.component('Badge', VPBadge)
        app.component('VPSwiper', VPSwiper)
      },
    }
  7. Install @cssnr/vitepress-swiper

    Install the VitePress Swiper plugin using your preferred package manager.
    # npm
    npm i @cssnr/vitepress-swiper
    
    # pnpm
    pnpm i @cssnr/vitepress-swiper
    
    # yarn
    yarn add @cssnr/vitepress-swiper
    
    # bun
    bun i @cssnr/vitepress-swiper
  8. Install and register VPSwiper in VitePress

    To use the VPSwiper component in VitePress, you must register it in your theme's entry point. If you do not have a .vitepress/theme/index.ts (or .js) file, create one. Import the component and its associated CSS, then register it as a global component within the enhanceApp hook.
    import DefaultTheme, { VPBadge } from 'vitepress/theme'
    import VPSwiper from '@cssnr/vitepress-swiper'
    import '@cssnr/vitepress-swiper/style.css'
    
    export default {
      ...DefaultTheme,
      enhanceApp({ app }) {
        app.component('Badge', VPBadge)
        app.component('VPSwiper', VPSwiper)
      },
    }
  9. Enable a custom theme in VitePress

    VitePress enables a custom theme when it detects a theme entry file at .vitepress/theme/index.js or .vitepress/theme/index.ts. When this file exists, VitePress uses the custom theme instead of the default theme.
    . 
    ├─ docs                # project root
    │  ├─ .vitepress
    │  │  ├─ theme
    │  │  │  └─ index.js   # theme entry
    │  │  └─ config.js     # config file
    │  └─ index.md
    └─ package.json
  10. Consume an external npm theme

    To use a theme distributed via npm, import and re-export it from your .vitepress/theme/index.js. If the theme provides a base configuration, extend it in your .vitepress/config.ts using the extends property.
    // .vitepress/theme/index.js
    import Theme from 'awesome-vitepress-theme'
    export default Theme
    // .vitepress/config.ts
    import baseConfig from 'awesome-vitepress-theme/config'
    import { defineConfig } from 'vitepress'
    import type { ThemeConfig } from 'awesome-vitepress-theme'
    
    export default defineConfig<ThemeConfig>({
      extends: baseConfig,
      themeConfig: {
        // Theme-specific options
      }
    })
    
  11. Badge component API reference

    The <Badge> component accepts the following props to control its appearance and content.
    interface Props {
      // The text to display inside the badge. Ignored if children/slot are provided.
      text?: string
    
      // The color style of the badge. Defaults to `tip`.
      // Matches markdown containers/alerts colors.
      type?: 'info' | 'note' | 'tip' | 'important' | 'caution' | 'warning' | 'danger'
    }
  12. Use the enhanceApp hook for global configuration

    The enhanceApp hook provides access to the Vue app instance and the VitePress router. It is used to register global components, integrate Vue libraries, or listen for route changes using router.onBeforeRouteChange and router.onAfterRouteChange.
    export default {
      enhanceApp({ router }) {
        router.onBeforeRouteChange = (to) => {
          console.log('navigating to', to)
          // Return false to cancel navigation
        }
    
        router.onAfterRouteChange = (to) => {
          console.log('navigated to', to)
        }
      }
    }