Saltar a contenido

VitePress Cheatsheet

■h1 contactoVitePress - Vite & Vue Powered Static Site Generator made "Clase de inscripción" VitePress es un generador de sitios estáticos (SSG) diseñado para construir sitios web rápidos y centrados en contenidos. Construido en la parte superior de Vite, proporciona una gran experiencia de desarrollador con el diseño y la personalización de Vue.js. ▪/p] ■/div titulada

########################################################################################################################################################################################################################################################## Copiar todos los comandos
########################################################################################################################################################################################################################################################## Generar PDF seleccionado/button

■/div titulada ■/div titulada

Cuadro de contenidos

Instalación

Inicio rápido

# Create new VitePress project
npm create vitepress@latest my-docs

# Navigate to project
cd my-docs

# Install dependencies
npm install

# Start development server
npm run docs:dev

Instalación manual

# Initialize npm project
npm init -y

# Install VitePress
npm install --save-dev vitepress

# Create basic structure
mkdir docs
echo '# Hello VitePress' > docs/index.md

Paquete.json Scripts

{
  "scripts": {
    "docs:dev": "vitepress dev docs",
    "docs:build": "vitepress build docs",
    "docs:preview": "vitepress preview docs"
  }
}

Comienzo

Configuración básica

# Create docs directory
mkdir docs

# Create index page
echo '# Welcome to My Documentation' > docs/index.md

# Create config file
mkdir docs/.vitepress

Configuración básica

// docs/.vitepress/config.js
export default {
  title: 'My Documentation',
  description: 'A comprehensive guide',
  themeConfig: {
    nav: [
      { text: 'Home', link: '/' },
      { text: 'Guide', link: '/guide/' },
      { text: 'API', link: '/api/' }
    ],
    sidebar: [
      {
        text: 'Guide',
        items: [
          { text: 'Introduction', link: '/guide/' },
          { text: 'Getting Started', link: '/guide/getting-started' }
        ]
      }
    ]
  }
}

Primeras Páginas

<!-- docs/index.md -->
---
layout: home
hero:
  name: My Project
  text: Amazing documentation
  tagline: Build something awesome
  actions:
    - theme: brand
      text: Get Started
      link: /guide/
    - theme: alt
      text: View on GitHub
      link: https://github.com/user/repo
features:
  - title: Fast
    details: Built with Vite for lightning-fast development
  - title: Flexible
    details: Customize with Vue.js components
  - title: SEO Friendly
    details: Static site generation for better SEO
---
<!-- docs/guide/index.md -->
# Introduction

Welcome to the guide section of our documentation.

## What is this project?

This project helps you build amazing things.

## Quick Start

1. Install the package
2. Configure your settings
3. Start building

Estructura del proyecto

Estructura básica

docs/
├── .vitepress/
   ├── config.js          # Configuration file
   ├── theme/             # Custom theme
   └── cache/             # Build cache
├── guide/
   ├── index.md
   ├── getting-started.md
   └── advanced.md
├── api/
   ├── index.md
   └── reference.md
├── public/                # Static assets
   ├── images/
   └── favicon.ico
└── index.md              # Homepage

Estructura avanzada

docs/
├── .vitepress/
   ├── config.js
   ├── config/
      ├── nav.js
      ├── sidebar.js
      └── plugins.js
   ├── theme/
      ├── index.js
      ├── components/
      ├── styles/
      └── layouts/
   ├── components/        # Global components
   └── public/           # Theme assets
├── en/                   # English docs
├── zh/                   # Chinese docs
├── guide/
├── api/
├── examples/
└── index.md

Configuración

Configuración básica

// docs/.vitepress/config.js
export default {
  // Site metadata
  title: 'VitePress',
  description: 'Vite & Vue powered static site generator',
  lang: 'en-US',
  base: '/', // Base URL for deployment

  // Theme configuration
  themeConfig: {
    logo: '/logo.svg',
    siteTitle: 'My Docs',

    // Navigation
    nav: [
      { text: 'Home', link: '/' },
      { text: 'Guide', link: '/guide/' }
    ],

    // Sidebar
    sidebar: {
      '/guide/': [
        {
          text: 'Getting Started',
          items: [
            { text: 'Introduction', link: '/guide/' },
            { text: 'Installation', link: '/guide/installation' }
          ]
        }
      ]
    },

    // Social links
    socialLinks: [
      { icon: 'github', link: 'https://github.com/vuejs/vitepress' },
      { icon: 'twitter', link: 'https://twitter.com/vuejs' }
    ],

    // Footer
    footer: {
      message: 'Released under the MIT License.',
      copyright: 'Copyright © 2023 Evan You'
    }
  }
}

Configuración avanzada

// docs/.vitepress/config.js
import { defineConfig } from 'vitepress'

export default defineConfig({
  title: 'My Documentation',
  description: 'Comprehensive documentation',

  // Head tags
  head: [
    ['link', { rel: 'icon', href: '/favicon.ico' }],
    ['meta', { name: 'theme-color', content: '#3c8772' }],
    ['meta', { property: 'og:type', content: 'website' }],
    ['meta', { property: 'og:locale', content: 'en' }],
    ['script', { src: 'https://cdn.usefathom.com/script.js' }]
  ],

  // Build options
  srcDir: 'src',
  outDir: 'dist',
  cacheDir: '.vitepress/cache',

  // Markdown configuration
  markdown: {
    theme: 'material-theme-palenight',
    lineNumbers: true,
    config: (md) => {
      // Add markdown plugins
      md.use(require('markdown-it-footnote'))
    }
  },

  // Vite configuration
  vite: {
    plugins: [],
    server: {
      port: 3000
    }
  },

  // Build hooks
  buildEnd: (siteConfig) => {
    console.log('Build completed!')
  }
})

Configuración TipoScript

// docs/.vitepress/config.ts
import { defineConfig } from 'vitepress'

export default defineConfig({
  title: 'My Docs',
  description: 'TypeScript powered documentation',

  themeConfig: {
    nav: [
      { text: 'Home', link: '/' },
      { text: 'Guide', link: '/guide/' }
    ]
  }
})

Características de marcado

Marco básico

# Heading 1
## Heading 2
### Heading 3

**Bold text**
*Italic text*
~~Strikethrough~~

- Unordered list
- Item 2
  - Nested item

1. Ordered list
2. Item 2

[Link text](https://example.com)

![Image alt](./image.png)

`Inline code`

> Blockquote

Bloqueos de código

__CODE_BLOCK_13_javascript función hola() {} consola.log('Hola, VitePress!') }

```javascript{1,3-5}
// Destacado de la línea
función hola() {}
consola.log('Hola, VitePress!')
const name = 'VitePress '
`Hello, ${name}!`
}

Números de línea
función hola() {}
consola.log('Hola, VitePress!')
}
````

Containers aduaneros

```markdown ::: info This is an info box. :::

::: tip This is a tip. :::

::: warning This is a warning. :::

::: danger This is a dangerous warning. :::

::: details Click me to view the code javascript consola.log('Hola, VitePress!') :::

::: code-group javascript [config.js] por defecto de exportación {} nombre: 'config ' }

typescript [config.ts] por defecto de exportación {} nombre: 'config ' Como const ::: ```

Cuadros

markdown | Feature | VitePress | Other SSG | |---------|-----------|-----------| | Speed | ⚡ Fast | 🐌 Slow | | Vue | ✅ Yes | ❌ No | | Vite | ✅ Yes | ❌ No |

Expresiones de matemáticas

```markdown

The formula is \(E = mc^2\).

$$ \frac{1}{2} \times \frac{3}{4} = \frac{3}{8} $$ ```

Emoji

```markdown 🎉 🚀 ❤

VitePress is 🔥! ```

Frontmatter

Frontmatter básico

```markdown

title: Page Title description: Page description layout: doc


Page Content

This page has custom metadata. ```

Frontmatter avanzado

```markdown

title: Advanced Guide description: Learn advanced VitePress features layout: doc sidebar: true prev: text: 'Getting Started' link: '/guide/getting-started' next: text: 'Configuration' link: '/guide/configuration' editLink: true lastUpdated: true


Advanced Guide

Content goes here. ```

Hogar:

```markdown

layout: home hero: name: VitePress text: Vite & Vue powered static site generator tagline: Simple, powerful, and performant image: src: /logo-with-shadow.png alt: VitePress actions: - theme: brand text: Get Started link: /guide/what-is-vitepress - theme: alt text: View on GitHub link: https://github.com/vuejs/vitepress

features: - icon: ⚡️ title: Vite, The DX that can't be beat details: Feel the speed of Vite. Instant server start and lightning fast HMR. - icon: 💡 title: Designed to be simplicity first details: With Markdown-centered content, it's built to help you focus on writing. - icon: 🛠️ title: Power of Vue meets Markdown details: Enhance your content with all the features of Vue in Markdown.


```

Diseño personalizado

```markdown

layout: custom customData: foo: bar items: - name: Item 1 - name: Item 2


Custom Layout Page

This page uses a custom layout. ```

Routing

Routing basado en archivos

```bash

File structure determines routes

docs/ ├── index.md # -> / ├── guide/ │ ├── index.md # -> /guide/ │ ├── setup.md # -> /guide/setup │ └── advanced.md # -> /guide/advanced └── api/ ├── index.md # -> /api/ └── reference.md # -> /api/reference ```

Rutas dinámicas

javascript // docs/.vitepress/config.js export default { async paths() { const posts = await getPosts() return posts.map(post => ({ params: { id: post.id }, content: post.content })) } }

Metadatos de ruta

```markdown

title: Custom Title description: Custom description head: - - meta - property: og:title content: Custom OG Title - - meta - property: og:description content: Custom OG Description


Page Content

```

```vue

```

Theming

Personalización del tema por defecto

```javascript // docs/.vitepress/theme/index.js import DefaultTheme from 'vitepress/theme' import './custom.css'

export default { extends: DefaultTheme, enhanceApp({ app, router, siteData }) { // App-level enhancements app.component('MyComponent', MyComponent) } } ```

Custom CSS

```css /* docs/.vitepress/theme/custom.css */ :root { --vp-c-brand-1: #646cff; --vp-c-brand-2: #747bff; --vp-c-brand-3: #9499ff; }

.VPHero .name { background: linear-gradient(120deg, #bd34fe 30%, #41d1ff); -webkit-background-clip: text; -webkit-text-fill-color: transparent; }

/* Dark mode */ .dark { --vp-c-brand-1: #747bff; --vp-c-brand-2: #9499ff; } ```

Diseño personalizado

```vue

```

Configuración temática

```javascript // docs/.vitepress/config.js export default { themeConfig: { // Appearance appearance: 'dark', // 'dark' | false

// Logo
logo: '/logo.svg',
siteTitle: 'My Docs',

// Navigation
nav: [...],
sidebar: {...},

// Edit link
editLink: {
  pattern: 'https://github.com/user/repo/edit/main/docs/:path',
  text: 'Edit this page on GitHub'
},

// Last updated
lastUpdated: {
  text: 'Updated at',
  formatOptions: {
    dateStyle: 'full',
    timeStyle: 'medium'
  }
},

// Search
search: {
  provider: 'local'
}

} } ```

Componentes personalizados

Global Components

```vue

```

Componentes de registro

```javascript // docs/.vitepress/theme/index.js import DefaultTheme from 'vitepress/theme' import Badge from '../components/Badge.vue' import CodeGroup from '../components/CodeGroup.vue'

export default { extends: DefaultTheme, enhanceApp({ app }) { app.component('Badge', Badge) app.component('CodeGroup', CodeGroup) } } ```

Uso en Markdown

```markdown

API Reference

Methods

getData() v1.0+

Fetches data from the API.

javascript const data = await api.getData() __CODE_BLOCK_39_typescript const data: ApiResponse = await api.getData()

```

Componentes interactivos

```vue

```

javascript // docs/.vitepress/config.js export default { themeConfig: { nav: [ { text: 'Home', link: '/' }, { text: 'Guide', link: '/guide/' }, { text: 'API', link: '/api/' }, { text: 'Changelog', link: '/changelog' } ] } }_

javascript export default { themeConfig: { nav: [ { text: 'Home', link: '/' }, { text: 'Guide', items: [ { text: 'Getting Started', link: '/guide/' }, { text: 'Configuration', link: '/guide/configuration' }, { text: 'Deployment', link: '/guide/deployment' } ] }, { text: 'Reference', items: [ { text: 'API', items: [ { text: 'Runtime API', link: '/api/runtime' }, { text: 'Build API', link: '/api/build' } ] }, { text: 'Config', items: [ { text: 'Site Config', link: '/config/site' }, { text: 'Theme Config', link: '/config/theme' } ] } ] } ] } }

Enlaces externos

javascript export default { themeConfig: { nav: [ { text: 'Home', link: '/' }, { text: 'GitHub', link: 'https://github.com/user/repo' }, { text: 'Resources', items: [ { text: 'Documentation', link: '/docs/' }, { text: 'GitHub', link: 'https://github.com/user/repo' }, { text: 'Discord', link: 'https://discord.gg/invite' } ] } ] } }

Enlace activo coincidente

javascript export default { themeConfig: { nav: [ { text: 'Guide', link: '/guide/', activeMatch: '/guide/' // Matches /guide/* paths }, { text: 'API', link: '/api/', activeMatch: '^/api/' // Regex pattern } ] } }

Barra lateral básica

javascript // docs/.vitepress/config.js export default { themeConfig: { sidebar: [ { text: 'Getting Started', items: [ { text: 'Introduction', link: '/guide/' }, { text: 'Installation', link: '/guide/installation' }, { text: 'Quick Start', link: '/guide/quick-start' } ] }, { text: 'Advanced', items: [ { text: 'Configuration', link: '/guide/configuration' }, { text: 'Theming', link: '/guide/theming' }, { text: 'Deployment', link: '/guide/deployment' } ] } ] } }

Múltiples barras laterales

javascript export default { themeConfig: { sidebar: { '/guide/': [ { text: 'Guide', items: [ { text: 'Introduction', link: '/guide/' }, { text: 'Getting Started', link: '/guide/getting-started' } ] } ], '/api/': [ { text: 'API Reference', items: [ { text: 'Overview', link: '/api/' }, { text: 'Methods', link: '/api/methods' } ] } ] } } }_

Barra lateral plegable

javascript export default { themeConfig: { sidebar: [ { text: 'Getting Started', collapsed: false, // Expanded by default items: [ { text: 'Introduction', link: '/guide/' }, { text: 'Installation', link: '/guide/installation' } ] }, { text: 'Advanced Topics', collapsed: true, // Collapsed by default items: [ { text: 'Custom Themes', link: '/advanced/themes' }, { text: 'Plugins', link: '/advanced/plugins' } ] } ] } }

Barra lateral autogenerada

```javascript // docs/.vitepress/config.js import { generateSidebar } from './utils/sidebar'

export default { themeConfig: { sidebar: generateSidebar('docs') } }

// utils/sidebar.js import fs from 'fs' import path from 'path'

export function generateSidebar(dir) { const files = fs.readdirSync(dir) return files .filter(file => file.endsWith('.md')) .map(file => ({ text: file.replace('.md', ''), link: /${file.replace('.md', '')} })) } ```

Búsqueda

Búsqueda local

javascript // docs/.vitepress/config.js export default { themeConfig: { search: { provider: 'local', options: { translations: { button: { buttonText: 'Search', buttonAriaLabel: 'Search' }, modal: { noResultsText: 'No results found', resetButtonTitle: 'Reset search', footer: { selectText: 'to select', navigateText: 'to navigate' } } } } } } }

Algolia Buscar

javascript export default { themeConfig: { search: { provider: 'algolia', options: { appId: 'YOUR_APP_ID', apiKey: 'YOUR_API_KEY', indexName: 'YOUR_INDEX_NAME', placeholder: 'Search docs', translations: { button: { buttonText: 'Search', buttonAriaLabel: 'Search' } } } } } }

Búsqueda personalizada

```vue

```

Internacionalización

Configuración de lenguaje múltiple

```javascript // docs/.vitepress/config.js export default { locales: { root: { label: 'English', lang: 'en', title: 'VitePress', description: 'Vite & Vue powered static site generator' }, zh: { label: '简体中文', lang: 'zh-CN', title: 'VitePress', description: 'Vite & Vue 驱动的静态站点生成器', themeConfig: { nav: [ { text: '首页', link: '/zh/' }, { text: '指南', link: '/zh/guide/' } ], sidebar: { '/zh/guide/': [ { text: '指南', items: [ { text: '介绍', link: '/zh/guide/' }, { text: '快速开始', link: '/zh/guide/getting-started' } ] } ] } } } },

themeConfig: { nav: [ { text: 'Home', link: '/' }, { text: 'Guide', link: '/guide/' } ], sidebar: { '/guide/': [ { text: 'Guide', items: [ { text: 'Introduction', link: '/guide/' }, { text: 'Getting Started', link: '/guide/getting-started' } ] } ] } } } ```

Estructura del directorio para i18n

bash docs/ ├── .vitepress/ │ └── config.js ├── index.md # English homepage ├── guide/ │ ├── index.md │ └── getting-started.md └── zh/ ├── index.md # Chinese homepage └── guide/ ├── index.md └── getting-started.md

Cambio de idioma

```vue

```

Despliegue

Hosting estático

```bash

Build for production

npm run docs:build

Output directory: docs/.vitepress/dist

Deploy this directory to your hosting provider

```

Páginas de GitHub

```yaml

.github/workflows/deploy.yml

name: Deploy VitePress site to Pages

on: push: branches: [main] workflow_dispatch:

permissions: contents: read pages: write id-token: write

concurrency: group: pages cancel-in-progress: false

jobs: build: runs-on: ubuntu-latest steps: - name: Checkout uses: actions/checkout@v3 with: fetch-depth: 0

  - name: Setup Node
    uses: actions/setup-node@v3
    with:
      node-version: 18
      cache: npm

  - name: Setup Pages
    uses: actions/configure-pages@v3

  - name: Install dependencies
    run: npm ci

  - name: Build with VitePress
    run: npm run docs:build

  - name: Upload artifact
    uses: actions/upload-pages-artifact@v2
    with:
      path: docs/.vitepress/dist

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@v2 ```

Netlify

```toml

netlify.toml

[build] command = "npm run docs:build" publish = "docs/.vitepress/dist"

[[redirects]] from = "/*" to = "/index.html" status = 200 ```

Vercel

json { "buildCommand": "npm run docs:build", "outputDirectory": "docs/.vitepress/dist" }

Dominio personalizado

```javascript // docs/.vitepress/config.js export default { base: '/my-project/', // For GitHub Pages subdirectory // base: '/', // For custom domain

head: [ ['link', { rel: 'canonical', href: 'https://mydomain.com' }] ] } ```

API Referencia

Datos del sitio

```vue

```

Página

```vue

```

Datos temáticos

```vue

```

Router

```vue

```

Plugins

Plugins Markdown

javascript // docs/.vitepress/config.js export default { markdown: { config: (md) => { // Add markdown-it plugins md.use(require('markdown-it-footnote')) md.use(require('markdown-it-deflist')) md.use(require('markdown-it-abbr')) md.use(require('markdown-it-emoji')) md.use(require('markdown-it-container'), 'custom') } } }_

Vite Plugins

```javascript // docs/.vitepress/config.js import { defineConfig } from 'vitepress'

export default defineConfig({ vite: { plugins: [ // Add Vite plugins { name: 'custom-plugin', configResolved(config) { // Plugin logic } } ] } }) ```

Ejemplo de plugin personalizado

```javascript // plugins/reading-time.js export function readingTimePlugin(md) { md.core.ruler.push('reading-time', (state) => { const content = state.src const wordsPerMinute = 200 const words = content.split(/\s+/).length const readingTime = Math.ceil(words / wordsPerMinute)

// Add to env for use in templates
state.env.readingTime = readingTime

}) }

// docs/.vitepress/config.js import { readingTimePlugin } from './plugins/reading-time.js'

export default { markdown: { config: (md) => { md.use(readingTimePlugin) } } } ```

Configuración avanzada

Optimización de la construcción

javascript // docs/.vitepress/config.js export default { vite: { build: { minify: 'terser', rollupOptions: { output: { manualChunks: { vue: ['vue'], vendor: ['lodash', 'axios'] } } } } } }

Etiquetas de la cabeza personalizada

javascript export default { head: [ ['meta', { name: 'author', content: 'Your Name' }], ['meta', { name: 'keywords', content: 'vitepress, vue, documentation' }], ['link', { rel: 'icon', href: '/favicon.ico' }], ['link', { rel: 'manifest', href: '/manifest.json' }], ['script', { src: 'https://analytics.example.com/script.js' }] ] }

Medio ambiente

javascript // docs/.vitepress/config.js export default { define: { __VERSION__: JSON.stringify(process.env.npm_package_version), __BUILD_TIME__: JSON.stringify(new Date().toISOString()) } }

Construir ganchos

```javascript export default { buildStart() { console.log('Build started') },

buildEnd(siteConfig) { console.log('Build completed') // Generate sitemap, RSS feed, etc. },

postRender(context) { // Post-render processing } } ```

Ejecución

Bundle Analysis

```bash

Install bundle analyzer

npm install --save-dev rollup-plugin-analyzer

Add to vite config

docs/.vitepress/config.js

export default { vite: { build: { rollupOptions: { plugins: [ require('rollup-plugin-analyzer')() ] } } } } ```

Lazy Cargando

```vue

```

Optimización de imagen

```markdown

Hero Image

Hero Image ```

Caching Strategy

javascript // docs/.vitepress/config.js export default { vite: { build: { rollupOptions: { output: { entryFileNames: 'assets/[name].[hash].js', chunkFileNames: 'assets/[name].[hash].js', assetFileNames: 'assets/[name].[hash].[ext]' } } } } }

Buenas prácticas

Content Organization

```bash

Recommended structure

docs/ ├── .vitepress/ ├── guide/ │ ├── index.md # Overview │ ├── getting-started.md │ ├── configuration.md │ └── advanced.md ├── api/ │ ├── index.md │ ├── methods.md │ └── types.md ├── examples/ ├── changelog.md └── index.md ```

SEO Optimización

```javascript // docs/.vitepress/config.js export default { head: [ ['meta', { name: 'description', content: 'Your site description' }], ['meta', { property: 'og:title', content: 'Your Site Title' }], ['meta', { property: 'og:description', content: 'Your site description' }], ['meta', { property: 'og:image', content: '/og-image.jpg' }], ['meta', { name: 'twitter:card', content: 'summary_large_image' }], ['link', { rel: 'canonical', href: 'https://yoursite.com' }] ],

// Generate sitemap sitemap: { hostname: 'https://yoursite.com' } } ```

Prácticas óptimas de rendimiento

  • Optimizar imágenes con formatos y tamaños adecuados
  • Use carga perezosa para componentes pesados
  • Minimizar el tamaño del paquete con el afeitado del árbol
  • ** Enable caching** con cabeceras adecuadas
  • Use CDN para activos estáticos

Prácticas óptimas del contenido

  • Epígrafes claros para una mejor navegación
  • Use formato consistente en páginas
  • Include code examples with proper syntax highlighting
  • Agregar funcionalidad de búsqueda para una mejor desvesibilidad
  • Mantenga una estructura consistente de navegación

-...

Resumen

VitePress es un potente generador de sitios estáticos que combina la velocidad de Vite con la flexibilidad de Vue.js. Las características principales incluyen:

  • Fast Development: Lightning-fast HMR alimentado por Vite
  • Vue-Powered: Soporte completo Vue.js para componentes interactivos
  • Marcdown-Centered: Concéntrate en el contenido con características de marcado mejoradas
  • Personalizado: Sistema flexible de identificación y componente
  • SEO-Friendly: Generación estatica del sitio con etiquetas meta adecuadas
  • TypeScript Support: Integración TipoScript de primera clase
  • ** Internacionalización**: Apoyo integrado en varios idiomas

Al aprovechar las capacidades de VitePress y seguir las mejores prácticas, puede crear sitios de documentación rápidos, hermosos y sostenibles que proporcionan una excelente experiencia de usuario.

" copia de la funciónToClipboard() {} comandos const = document.querySelectorAll('code'); que todos losCommands = '; comandos. paraCada(cmd = confianza allCommands += cmd.textContent + '\n'); navigator.clipboard.writeText(allCommands); alerta ('Todos los comandos copiados a portapapeles!'); }

función generaPDF() { ventana.print(); } ■/script título