Skip to content

Best Practices

Learn the best practices for building maintainable, performant, and user-friendly VitePress sites.

Content Organization

File Structure

Organize your content logically and consistently:

docs/
├── .vitepress/
│   ├── config.ts
│   └── theme/
├── guide/
│   ├── index.md
│   ├── getting-started.md
│   └── advanced/
│       ├── index.md
│       └── customization.md
├── api/
│   ├── index.md
│   └── reference.md
├── examples/
└── public/
    ├── images/
    └── assets/

Naming Conventions

  • Files: Use kebab-case (getting-started.md)
  • Directories: Use kebab-case (best-practices/)
  • Images: Descriptive names (hero-banner.jpg)
  • URLs: Clean, readable paths (/guide/getting-started)

Content Hierarchy

markdown
# Page Title (H1) - Only one per page
Brief introduction paragraph.

## Main Section (H2)
Content for main sections.

### Subsection (H3)
Detailed information.

#### Details (H4)
Specific details when needed.

Writing Guidelines

Clear and Concise Writing

  • Start with the goal: What will users accomplish?
  • Use active voice: "Configure the settings" vs "Settings can be configured"
  • Be specific: "Click the Save button" vs "Save your changes"
  • Avoid jargon: Explain technical terms when first used

Progressive Disclosure

Structure content from simple to complex:

markdown
# Getting Started

## Quick Start (Simple)
Basic setup for immediate results.

## Configuration (Intermediate)
Customization options.

## Advanced Usage (Complex)
Power user features.

Code Examples

Always include complete, runnable examples:

js
// ❌ Incomplete example
const config = {
  title: 'My Site'
}

// ✅ Complete example
// .vitepress/config.js
export default {
  title: 'My Site',
  description: 'A comprehensive guide',
  themeConfig: {
    nav: [
      { text: 'Home', link: '/' },
      { text: 'Guide', link: '/guide/' }
    ]
  }
}

Configuration Best Practices

Modular Configuration

Split large configurations into modules:

js
// config/nav.js
export const nav = [
  { text: 'Guide', link: '/guide/' },
  { text: 'API', link: '/api/' }
]

// config/sidebar.js
export const sidebar = {
  '/guide/': [
    // sidebar items
  ]
}

// .vitepress/config.js
import { nav } from './config/nav.js'
import { sidebar } from './config/sidebar.js'

export default {
  themeConfig: {
    nav,
    sidebar
  }
}

Environment-Specific Settings

js
const isDev = process.env.NODE_ENV === 'development'

export default {
  base: isDev ? '/' : '/my-project/',
  
  head: [
    // Only include analytics in production
    ...(!isDev ? [
      ['script', { src: 'https://analytics.example.com/script.js' }]
    ] : [])
  ]
}

Performance Configuration

js
export default {
  // Optimize build output
  build: {
    minify: 'terser',
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['vue'],
          utils: ['lodash', 'date-fns']
        }
      }
    }
  },
  
  // Enable compression
  vite: {
    build: {
      cssCodeSplit: true,
      sourcemap: false
    }
  }
}

Theme Customization

CSS Organization

Structure your custom styles:

css
/* .vitepress/theme/styles/variables.css */
:root {
  /* Brand colors */
  --vp-c-brand: #646cff;
  --vp-c-brand-light: #747bff;
  --vp-c-brand-dark: #535bf2;
  
  /* Custom spacing */
  --content-max-width: 1200px;
  --sidebar-width: 280px;
}

/* .vitepress/theme/styles/components.css */
.custom-component {
  /* Component-specific styles */
}

/* .vitepress/theme/styles/utilities.css */
.text-center { text-align: center; }
.mb-4 { margin-bottom: 1rem; }

Component Development

Create reusable Vue components:

vue
<!-- .vitepress/theme/components/FeatureCard.vue -->
<template>
  <div class="feature-card">
    <div class="feature-icon">
      <component :is="icon" />
    </div>
    <h3>{{ title }}</h3>
    <p>{{ description }}</p>
  </div>
</template>

<script setup lang="ts">
interface Props {
  icon: string
  title: string
  description: string
}

defineProps<Props>()
</script>

<style scoped>
.feature-card {
  padding: 2rem;
  border: 1px solid var(--vp-c-divider);
  border-radius: 8px;
  text-align: center;
  transition: transform 0.2s ease;
}

.feature-card:hover {
  transform: translateY(-2px);
}

.feature-icon {
  font-size: 2rem;
  margin-bottom: 1rem;
  color: var(--vp-c-brand);
}
</style>

Performance Optimization

Image Optimization

  • Use appropriate formats: WebP for modern browsers, JPEG/PNG as fallback
  • Optimize file sizes: Compress images without quality loss
  • Responsive images: Provide multiple sizes for different devices
  • Lazy loading: Load images as needed
markdown
<!-- Optimized image with alt text -->
![VitePress Dashboard](./images/dashboard-optimized.webp "VitePress admin dashboard")

<!-- Multiple sizes for responsive design -->
<picture>
  <source media="(min-width: 768px)" srcset="/images/hero-large.webp">
  <source media="(min-width: 480px)" srcset="/images/hero-medium.webp">
  <img src="/images/hero-small.webp" alt="VitePress hero image">
</picture>

Code Splitting

Split large pages into smaller chunks:

js
// Use dynamic imports for heavy components
const HeavyComponent = defineAsyncComponent(() => 
  import('./components/HeavyComponent.vue')
)

SEO Best Practices

Meta Tags

Include comprehensive meta information:

js
// .vitepress/config.js
export default {
  head: [
    // Basic meta tags
    ['meta', { name: 'description', content: 'VitePress development guide' }],
    ['meta', { name: 'keywords', content: 'vitepress, vue, documentation' }],
    
    // Open Graph
    ['meta', { property: 'og:title', content: 'VitePress Guide' }],
    ['meta', { property: 'og:description', content: 'Complete VitePress guide' }],
    ['meta', { property: 'og:image', content: '/og-image.jpg' }],
    
    // Twitter Card
    ['meta', { name: 'twitter:card', content: 'summary_large_image' }],
    
    // Favicon
    ['link', { rel: 'icon', href: '/favicon.ico' }]
  ]
}

Structured Data

Add JSON-LD structured data:

js
export default {
  head: [
    ['script', { type: 'application/ld+json' }, JSON.stringify({
      '@context': 'https://schema.org',
      '@type': 'WebSite',
      name: 'VitePress Guide',
      description: 'Comprehensive VitePress documentation',
      url: 'https://vitepress-guide.com'
    })]
  ]
}

Accessibility

Semantic HTML

Use proper HTML structure and provide descriptive alt text for images:

markdown
# Main Heading (becomes h1)

## Section Heading (becomes h2)

### Subsection (becomes h3)

<!-- ✅ Descriptive alt text -->
![VitePress configuration panel showing navigation settings](./screenshot.png)

Keyboard Navigation

Ensure all interactive elements are keyboard accessible:

vue
<template>
  <button 
    @click="handleClick"
    @keydown.enter="handleClick"
    @keydown.space.prevent="handleClick"
  >
    Accessible Button
  </button>
</template>

Security

Content Security Policy

Implement CSP headers:

js
export default {
  head: [
    ['meta', { 
      'http-equiv': 'Content-Security-Policy', 
      content: "default-src 'self'; script-src 'self' 'unsafe-inline'"
    }]
  ]
}

Configure external links safely:

markdown
[External Link](https://example.com){target="_blank" rel="noopener noreferrer"}

Testing and Quality Assurance

Content Review Checklist

  • [ ] All links work correctly
  • [ ] Images load and have alt text
  • [ ] Code examples are complete and tested
  • [ ] Responsive design works on mobile
  • [ ] Search functionality works
  • [ ] Navigation is intuitive

Performance Testing

bash
# Build and analyze
npm run build
npm run preview

# Test with Lighthouse
npx lighthouse http://localhost:4173 --output html

# Check bundle size
npx vitepress build --analyze

Accessibility Testing

  • Use screen reader testing
  • Check keyboard navigation
  • Validate color contrast ratios
  • Test with accessibility tools

Maintenance

Regular Updates

  • Keep VitePress and dependencies updated
  • Review and update content regularly
  • Monitor site performance
  • Check for broken links
  • Update screenshots and examples

Documentation Lifecycle

  1. Plan: Define content goals and audience
  2. Write: Create clear, helpful content
  3. Review: Test and validate content
  4. Publish: Deploy to production
  5. Maintain: Regular updates and improvements

Version Control

  • Use meaningful commit messages
  • Tag releases appropriately
  • Maintain changelog
  • Use branching strategy for content updates

Collaboration

Team Workflows

  • Establish content style guide
  • Use pull request reviews
  • Set up automated testing
  • Create content templates
  • Document contribution process

Content Guidelines

  • Consistent voice and tone
  • Regular content audits
  • User feedback integration
  • Analytics-driven improvements

Monitoring and Analytics

Key Metrics

  • Page load times
  • User engagement
  • Search usage
  • Popular content
  • Error rates

Tools Integration

js
// Google Analytics
export default {
  head: [
    ['script', { async: true, src: 'https://www.googletagmanager.com/gtag/js?id=GA_ID' }],
    ['script', {}, `
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', 'GA_ID');
    `]
  ]
}

Conclusion

Following these best practices will help you create:

  • Maintainable: Easy to update and extend
  • Performant: Fast loading and responsive
  • Accessible: Usable by everyone
  • Secure: Protected against common vulnerabilities
  • User-friendly: Intuitive and helpful

Remember that best practices evolve with technology and user needs. Stay updated with the latest VitePress features and web standards.

Next Steps


These best practices are continuously updated based on community feedback and evolving web standards.

VitePress Development Guide