Skip to content

[[[[Switch to English]]]]

代码高亮

VitePress 提供了由 Shiki 驱动的强大的语法高亮功能,支持数百种编程语言和主题。

基本语法高亮

JavaScript

js
function greet(name) {
  return `Hello, ${name}!`
}

const message = greet('World')
console.log(message)

TypeScript

ts
interface User {
  id: number
  name: string
  email: string
}

function createUser(userData: Partial<User>): User {
  return {
    id: Date.now(),
    name: userData.name || 'Anonymous',
    email: userData.email || ''
  }
}

Vue

vue
<!-- Vue 组件示例 -->
<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <button @click="increment">Count: {{ count }}</button>
  </div>
</template>

<script setup>
import { ref } from 'vue'

const msg = ref('Hello VitePress!')
const count = ref(0)

const increment = () => {
  count.value++
}
</script>

<style scoped>
.hello {
  text-align: center;
  padding: 20px;
}
</style>

CSS

css
.container {
  display: flex;
  flex-direction: column;
  gap: 1rem;
  padding: 1rem;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border-radius: 8px;
}

.button {
  background: #42b883;
  color: white;
  border: none;
  padding: 0.5rem 1rem;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.button:hover {
  background: #369870;
}

行高亮

单行

js
function processData(data) {
  const result = data.map(item => item * 2)  // 高亮此行
  return result.filter(item => item > 10)
}

多行

js
const config = {  // 高亮第 1 行
  name: 'My App',
  version: '1.0.0',  // 高亮第 3-4 行
  author: 'John Doe'
}

行范围

js
export default {
  data() {
    return {
      message: 'Hello',
      count: 0
    }
  },
  methods: {
    increment() {
      this.count++
    }
  }
}

行号

启用行号以提高代码可读性:

js
function fibonacci(n) {
  if (n <= 1) return n
  return fibonacci(n - 1) + fibonacci(n - 2)
}

特定语言功能

Python

python
def fibonacci(n):
    """Calculate the nth Fibonacci number."""
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

# 列表推导式示例
squares = [x**2 for x in range(10) if x % 2 == 0]

# 类定义
class Calculator:
    def __init__(self):
        self.result = 0
    
    def add(self, x):
        self.result += x
        return self

Rust

rust
fn fibonacci(n: u32) -> u32 {
    match n {
        0 => 0,
        1 => 1,
        _ => fibonacci(n - 1) + fibonacci(n - 2),
    }
}

struct Point {
    x: f64,
    y: f64,
}

impl Point {
    fn new(x: f64, y: f64) -> Self {
        Point { x, y }
    }
    
    fn distance(&self, other: &Point) -> f64 {
        ((self.x - other.x).powi(2) + (self.y - other.y).powi(2)).sqrt()
    }
}

Go

go
package main

import (
    "fmt"
    "math"
)

type Point struct {
    X, Y float64
}

func (p Point) Distance(other Point) float64 {
    dx := p.X - other.X
    dy := p.Y - other.Y
    return math.Sqrt(dx*dx + dy*dy)
}

func fibonacci(n int) int {
    if n <= 1 {
        return n
    }
    return fibonacci(n-1) + fibonacci(n-2)
}

func main() {
    p1 := Point{1, 2}
    p2 := Point{4, 6}
    fmt.Printf("Distance: %.2f\n", p1.Distance(p2))
}

自定义主题

暗色主题示例

js
// 暗色主题配置
export default {
  markdown: {
    theme: {
      light: 'github-light',
      dark: 'github-dark'
    }
  }
}

自定义配色方案

css
/* 自定义语法高亮颜色 */
:root {
  --shiki-color-text: #d4d4d4;
  --shiki-color-background: #1e1e1e;
  --shiki-token-constant: #9cdcfe;
  --shiki-token-string: #ce9178;
  --shiki-token-comment: #6a9955;
  --shiki-token-keyword: #569cd6;
  --shiki-token-parameter: #9cdcfe;
  --shiki-token-function: #dcdcaa;
  --shiki-token-string-expression: #ce9178;
  --shiki-token-punctuation: #d4d4d4;
  --shiki-token-link: #4ec9b0;
}

高级功能

差异高亮

diff
function processData(data) {
-  const result = data.map(item => item * 2)
+  const result = data
+    .filter(item => item > 0)
+    .map(item => item * 2)
   return result
}

内联代码

使用带有语法高亮的 inline codeconst message = 'Hello'

代码组

比较不同的实现:

js
function fibonacci(n) {
  if (n <= 1) return n
  return fibonacci(n - 1) + fibonacci(n - 2)
}
ts
function fibonacci(n: number): number {
  if (n <= 1) return n
  return fibonacci(n - 1) + fibonacci(n - 2)
}
python
def fibonacci(n):
    if n <= 1:
        return n
    return fibonacci(n - 1) + fibonacci(n - 2)

性能提示

优化大型代码块

对于大型代码文件,考虑使用导入:

js
// 导入大型代码文件
import largeFile from '@/examples/large-file.js'

懒加载

按需加载代码示例:

js
// 懒加载组件
const LazyComponent = () => import('./LazyComponent.vue')

最佳实践

语言规范

始终指定语言以获得更好的高亮:

js
// 推荐 - 指定语言
const message = 'Hello'
// 避免 - 未指定语言
const message = 'Hello'

行高亮

适度使用行高亮以引起注意:

js
function processUser(user) {
  // 验证用户数据
  if (!user.name || !user.email) {  // 高亮验证
    throw new Error('Invalid user data')
  }
  return user
}

代码注释

在代码示例中使用有意义的注释:

js
// 计算数组的总和
function sum(arr) {
  return arr.reduce((acc, val) => acc + val, 0)
}

// 示例用法
const numbers = [1, 2, 3, 4, 5]
const total = sum(numbers) // 返回 15

支持的语言

VitePress 支持数百种编程语言,包括:

  • JavaScript/TypeScript
  • Python
  • Java
  • C/C++
  • Rust
  • Go
  • PHP
  • Ruby
  • Swift
  • Kotlin
  • 以及更多...

有关完整列表,请访问 Shiki 文档