VitePress 版本升级指南
VitePress 大版本升级时的 Breaking Changes 专题和迁移策略,帮助你安全地升级项目。
升级前的准备
1. 查看更新日志
bash
# 查看 VitePress 版本
npx vitepress --version
# 查看可用版本
npm view vitepress versions
# 查看 CHANGELOG
npx vitepress changelog2. 备份项目
bash
# 创建备份分支
git checkout -b backup-before-upgrade
git push origin backup-before-upgrade
# 切回主分支继续操作
git checkout main3. 创建测试分支
bash
git checkout -b upgrade-vitepress升级流程
推荐步骤
mermaid
graph TD
A[查看 CHANGELOG] --> B[创建测试分支]
B --> C[升级依赖版本]
C --> D[处理 Breaking Changes]
D --> E[运行构建测试]
E --> F{构建是否通过?}
F -->|是| G[功能回归测试]
F -->|否| D
G --> H{功能是否正常?}
H -->|是| I[合并到主分支]
H -->|否| D升级命令
bash
# 升级到最新版
npm install vitepress@latest -D
# 升级到指定大版本
npm install vitepress@^2.0.0 -D
# 同时升级相关依赖
npm install vue@latest @vite-pwa/vitepress@latest -Dv1 → v2 Breaking Changes
配置文件变更
defineConfig 导入路径
ts
// v1
import { defineConfig } from 'vitepress'
// v2(不变,但类型更严格)
import { defineConfig } from 'vitepress'TypeScript 严格性
v2 的 defineConfig 对嵌套类型的校验更严格,之前被隐式 any 绕过的配置项现在会报类型错误。
侧边栏配置
ts
// v1
sidebar: {
'/guide/': [
{
text: '入门',
children: [ // v1 使用 children
{ text: '介绍', link: '/guide/intro' }
]
}
]
}
// v2
sidebar: {
'/guide/': [
{
text: '入门',
items: [ // v2 使用 items
{ text: '介绍', link: '/guide/intro' }
]
}
]
}collapsable → collapsed
ts
// v1
{ text: '入门', collapsable: true }
// v2
{ text: '入门', collapsed: true }注意
collapsed: true 表示默认折叠,而非"可折叠"。如需默认展开但仍可折叠,省略 collapsed 或设为 false。
侧边栏徽章(v2 新增)
v2 为侧边栏项新增 badge 字段:
ts
// v2 新增
sidebar: {
'/guide/': [
{
text: '入门',
items: [
{ text: '介绍', link: '/guide/intro' },
{ text: '快速开始', link: '/guide/quick-start', badge: { text: 'NEW', type: 'tip' } }
]
}
]
}主题配置变更
搜索配置
ts
// v1
themeConfig: {
algolia: {
apiKey: '...',
indexName: '...'
}
}
// v2
themeConfig: {
search: {
provider: 'algolia',
options: {
apiKey: '...',
indexName: '...'
}
}
}本地搜索增强
v2 的本地搜索支持更多选项:
ts
// v2
themeConfig: {
search: {
provider: 'local',
options: {
locales: {
zh: {
translations: {
button: { buttonText: '搜索文档' },
modal: { noResultsText: '无法找到相关结果' }
}
}
}
}
}
}编辑链接
ts
// v1
themeConfig: {
editLinks: true,
editLinkText: '编辑此页',
repo: 'user/repo'
}
// v2
themeConfig: {
editLink: {
pattern: 'https://github.com/user/repo/edit/main/docs/:path',
text: '编辑此页'
}
}各平台的 pattern 格式:
| 平台 | pattern |
|---|---|
| GitHub | https://github.com/user/repo/edit/main/docs/:path |
| GitLab | https://gitlab.com/user/repo/-/edit/main/docs/:path |
| Gitee | https://gitee.com/user/repo/edit/main/docs/:path |
| CNB | https://cnb.cool/user/repo/-/edit/main/docs/:path |
导航栏变更
ts
// v1 — 支持简单字符串格式
nav: [
{ text: '指南', link: '/guide/' }
]
// v2 — 统一为对象格式,支持 badge
nav: [
{ text: '指南', link: '/guide/' },
{ text: 'API', link: '/api/', badge: { text: 'Beta', type: 'warning' } }
]Markdown 配置变更
语法高亮
ts
// v1
markdown: {
lineNumbers: true
}
// v2
markdown: {
lineNumbers: true // 不变,但支持更多配置
}v2 新增的 Markdown 配置
ts
// v2
markdown: {
// 数学公式(v2 原生支持)
math: true,
// 脚注(v2 原生支持)
footnotes: true,
// Mermaid 图表(v2 原生支持)
mermaid: true,
}运行时 API 变更
useData 返回值
ts
// v1
const { site, page, theme, frontmatter } = useData()
// v2(返回值结构更丰富)
const { site, page, theme, frontmatter, lang, localePath } = useData()| 字段 | v1 | v2 | 说明 |
|---|---|---|---|
site | ✅ | ✅ | 站点级数据 |
page | ✅ | ✅ | 页面级数据 |
theme | ✅ | ✅ | 主题配置 |
frontmatter | ✅ | ✅ | 页面 frontmatter |
lang | ❌ | ✅ | 当前页面语言 |
localePath | ❌ | ✅ | 当前语言前缀路径 |
title | ❌ | ✅ | 页面标题(v2 新增便捷属性) |
description | ❌ | ✅ | 页面描述(v2 新增便捷属性) |
isDark | ❌ | ✅ | 是否暗色模式(可写 Ref) |
withBase
ts
// v1 - 从 vitepress 导入
import { withBase } from 'vitepress'
// v2 - 不变
import { withBase } from 'vitepress'新增:defineClientComponent
v2 新增 defineClientComponent,用于在 SSR 安全地引入仅客户端组件:
ts
// v2
import { defineClientComponent } from 'vitepress'
const ClientOnlyChart = defineClientComponent(() => {
return import('./Chart.vue')
})新增:createContentLoader
v2 新增数据加载器 API:
ts
// docs/components/data.data.ts
import { createContentLoader } from 'vitepress'
export default createContentLoader('posts/*.md', {
includeSrc: true,
transform(raw) {
return raw.sort((a, b) =>
+new Date(b.frontmatter.date) - +new Date(a.frontmatter.date)
)
}
})CSS 变量变更
v2 对部分 CSS 变量进行了重命名和层级调整:
| v1 变量 | v2 变量 | 说明 |
|---|---|---|
--vp-c-brand | --vp-c-brand-1 | 品牌主色 |
--vp-c-brand-light | --vp-c-brand-2 | 品牌浅色 |
--vp-c-brand-lighter | --vp-c-brand-3 | 品牌更浅色 |
--vp-c-brand-dark | --vp-c-brand-1 (暗色模式) | 品牌深色 |
--vp-c-brand-darker | --vp-c-brand-2 (暗色模式) | 品牌更深色 |
--vp-c-text | --vp-c-text-1 | 主要文本色 |
--vp-c-text-light | --vp-c-text-2 | 次要文本色 |
--vp-c-text-lighter | --vp-c-text-3 | 辅助文本色 |
--vp-c-bg | --vp-c-bg | 不变 |
--vp-c-bg-soft | --vp-c-bg-soft | 不变 |
--vp-code-block-bg | --vp-code-block-bg | 不变 |
重要
如果你的自定义样式中使用了 --vp-c-brand(无后缀),v2 中该变量已被移除,必须迁移到 --vp-c-brand-1。
迁移示例:
css
/* v1 */
.custom-component {
color: var(--vp-c-brand);
background: var(--vp-c-brand-light);
border-color: var(--vp-c-brand-lighter);
}
/* v2 */
.custom-component {
color: var(--vp-c-brand-1);
background: var(--vp-c-brand-2);
border-color: var(--vp-c-brand-3);
}构建配置变更
输出目录
ts
// v1 — 默认输出到 docs/.vitepress/dist
// v2 — 不变,但更推荐通过 vite.build.outDir 配置
export default defineConfig({
vite: {
build: {
outDir: '../dist' // 自定义输出目录
}
}
})MPA 模式
ts
// v2 新增 MPA 模式(适用于非 SPA 场景)
export default defineConfig({
mpa: true // 多页面应用模式
})已废弃的 API
| v1 API | v2 替代 | 说明 |
|---|---|---|
themeConfig.algolia | themeConfig.search | 搜索配置统一 |
themeConfig.editLinks | themeConfig.editLink | 编辑链接配置 |
themeConfig.repo | themeConfig.editLink.pattern | 仓库信息合并到编辑链接 |
themeConfig.docsRepo | themeConfig.editLink.pattern | 同上 |
themeConfig.docsBranch | themeConfig.editLink.pattern | 同上 |
themeConfig.docsDir | themeConfig.editLink.pattern | 同上 |
themeConfig.editLinkText | themeConfig.editLink.text | 编辑链接文案 |
sidebar.children | sidebar.items | 侧边栏子项命名 |
collapsable | collapsed | 拼写修正 |
themeConfig.nav 简单格式 | 对象格式 | 导航项统一为对象 |
--vp-c-brand(无后缀) | --vp-c-brand-1 | CSS 变量重命名 |
--vp-c-text | --vp-c-text-1 | CSS 变量重命名 |
--vp-c-text-light | --vp-c-text-2 | CSS 变量重命名 |
v2 新特性一览
升级到 v2 后,你可以利用以下新特性:
内容增强
| 特性 | 说明 |
|---|---|
| 原生数学公式 | markdown.math: true,无需安装 markdown-it-katex |
| 原生脚注 | markdown.footnotes: true,无需安装 markdown-it-footnote |
| 原生 Mermaid | markdown.mermaid: true,无需 vitepress-plugin-mermaid |
| 代码组语法 | ::: code-group 内联语法 |
| 行高亮增强 | 支持 {1,3-5} 更灵活的行号范围 |
功能增强
| 特性 | 说明 |
|---|---|
createContentLoader | 构建时数据加载,用于博客列表、标签页等 |
defineClientComponent | SSR 安全的仅客户端组件 |
| 侧边栏徽章 | 侧边栏项支持 badge 字段 |
| 导航栏徽章 | 导航栏项支持 badge 字段 |
| MPA 模式 | mpa: true 多页面应用模式 |
isDark | useData() 返回可写的暗色模式状态 |
性能提升
| 优化 | 说明 |
|---|---|
| 更快的冷启动 | Vite 5 底层优化 |
| 更小的包体积 | Tree-shaking 改进 |
| 更快的搜索 | 本地搜索引擎重写 |
| 懒加载优化 | 首屏加载更少资源 |
自动迁移脚本
对于大型项目,可以使用脚本批量处理 breaking changes:
ts
// scripts/migrate-v1-to-v2.ts
import fs from 'fs'
import path from 'path'
import glob from 'fast-glob'
// CSS 变量映射
const CSS_VAR_MAP: Record<string, string> = {
'--vp-c-brand': '--vp-c-brand-1',
'--vp-c-brand-light': '--vp-c-brand-2',
'--vp-c-brand-lighter': '--vp-c-brand-3',
'--vp-c-brand-dark': '--vp-c-brand-1',
'--vp-c-brand-darker': '--vp-c-brand-2',
'--vp-c-text': '--vp-c-text-1',
'--vp-c-text-light': '--vp-c-text-2',
'--vp-c-text-lighter': '--vp-c-text-3',
}
// 配置文件文本替换
const CONFIG_REPLACEMENTS: [RegExp, string][] = [
[/children:/g, 'items:'],
[/collapsable:/g, 'collapsed:'],
]
async function migrateCssFiles(dir: string): Promise<number> {
const files = await glob(['**/*.css', '**/*.vue'], { cwd: dir, absolute: true })
let count = 0
for (const file of files) {
let content = fs.readFileSync(file, 'utf-8')
let modified = false
for (const [oldVar, newVar] of Object.entries(CSS_VAR_MAP)) {
if (content.includes(oldVar)) {
content = content.replaceAll(`var(${oldVar})`, `var(${newVar})`)
modified = true
}
}
if (modified) {
fs.writeFileSync(file, content, 'utf-8')
count++
console.log(` ✅ Migrated CSS vars: ${path.relative(dir, file)}`)
}
}
return count
}
async function migrateConfig(dir: string): Promise<number> {
const files = await glob(['**/*.mts', '**/*.ts', '**/*.js'], {
cwd: dir,
absolute: true,
ignore: ['**/node_modules/**', '**/dist/**']
})
let count = 0
for (const file of files) {
let content = fs.readFileSync(file, 'utf-8')
let modified = false
for (const [pattern, replacement] of CONFIG_REPLACEMENTS) {
if (pattern.test(content)) {
content = content.replace(pattern, replacement)
modified = true
}
}
if (modified) {
fs.writeFileSync(file, content, 'utf-8')
count++
console.log(` ✅ Migrated config: ${path.relative(dir, file)}`)
}
}
return count
}
async function main() {
const root = process.argv[2] || 'docs'
console.log(`🚀 Migrating VitePress v1 → v2 in ${root}/\n`)
console.log('📦 Migrating CSS variables...')
const cssCount = await migrateCssFiles(root)
console.log(` → ${cssCount} files updated\n`)
console.log('📦 Migrating config files...')
const configCount = await migrateConfig(root)
console.log(` → ${configCount} files updated\n`)
console.log('✅ Migration complete!')
console.log('\n⚠️ Manual steps required:')
console.log(' 1. Update themeConfig.algolia → themeConfig.search')
console.log(' 2. Update themeConfig.editLinks → themeConfig.editLink')
console.log(' 3. Update themeConfig.repo → themeConfig.editLink.pattern')
console.log(' 4. Review all changes with git diff')
console.log(' 5. Run npm run build to verify')
}
main()使用方式:
bash
# 安装依赖
npm install -D fast-glob tsx
# 运行迁移脚本
npx tsx scripts/migrate-v1-to-v2.ts docs升级检查清单
必须修改
- [ ]
sidebar.children→sidebar.items - [ ]
collapsable→collapsed - [ ]
themeConfig.algolia→themeConfig.search - [ ]
themeConfig.editLinks→themeConfig.editLink - [ ]
themeConfig.repo→themeConfig.editLink.pattern - [ ]
--vp-c-brand→--vp-c-brand-1(所有 CSS 文件) - [ ]
--vp-c-text→--vp-c-text-1(所有 CSS 文件) - [ ] 检查所有已废弃 API 是否已替换
建议修改
- [ ] 搜索配置使用
provider语法 - [ ] 编辑链接使用
pattern语法 - [ ] 导航项统一为对象格式
- [ ] 利用新增的
localePath、lang、isDark等运行时 API - [ ] 替换
vitepress-plugin-mermaid为原生markdown.mermaid - [ ] 替换
markdown-it-katex为原生markdown.math - [ ] 替换
markdown-it-footnote为原生markdown.footnotes - [ ] 利用
createContentLoader替代自定义数据加载
验证测试
- [ ]
npm run dev开发服务器正常启动 - [ ]
npm run build构建成功 - [ ] 所有页面路由正常访问
- [ ] 侧边栏和导航栏显示正确
- [ ] 搜索功能正常
- [ ] 亮色/暗色模式切换正常
- [ ] 移动端响应式正常
- [ ] 自定义 CSS 变量颜色正确
- [ ] 第三方插件兼容
回滚策略
如果升级后遇到无法解决的问题:
bash
# 方案一:回退版本
npm install vitepress@1.x -D
# 方案二:回退 Git 分支
git checkout main
git branch -D upgrade-vitepress
# 方案三:使用备份分支
git checkout backup-before-upgrade渐进式升级
对于大型项目,建议渐进式升级:
1. 先升级 Patch 版本
bash
npm install vitepress@~1.x -D2. 再升级 Minor 版本
bash
npm install vitepress@^1.x -D3. 最后升级 Major 版本
bash
npm install vitepress@^2.0.0 -D4. 逐页验证
bash
# 构建并逐页检查
npm run build
npx vitepress preview docs
# 使用 Playwright 自动化回归测试
npx playwright test常见升级问题
构建报错:模块找不到
bash
# 清除缓存重装
rm -rf node_modules package-lock.json
npm install样式丢失
v2 调整了部分 CSS 变量名,检查自定义样式:
css
/* 检查是否有使用已废弃的变量 */
/* v1 */ --vp-c-brand → /* v2 */ --vp-c-brand-1
/* v1 */ --vp-c-brand-light → /* v2 */ --vp-c-brand-2
/* v1 */ --vp-c-text → /* v2 */ --vp-c-text-1
/* v1 */ --vp-c-text-light → /* v2 */ --vp-c-text-2插件不兼容
bash
# 检查插件兼容版本
npm view vitepress-plugin-mermaid peerDependencies
# 升级所有相关插件
npm install vitepress-plugin-mermaid@latest -D
# 对于 v2 原生支持的功能,考虑移除插件
# 如:mermaid → markdown.mermaid: true
# katex → markdown.math: true搜索配置报错
ts
// ❌ v1 格式,v2 报错
themeConfig: {
algolia: { apiKey: '...', indexName: '...' }
}
// ✅ v2 格式
themeConfig: {
search: {
provider: 'algolia',
options: { apiKey: '...', indexName: '...' }
}
}暗色模式颜色异常
v2 的暗色模式下品牌色使用 --vp-c-brand-1 而非 --vp-c-brand-dark:
css
/* v1 暗色模式 */
.dark {
--vp-c-brand: var(--vp-c-brand-dark);
}
/* v2 暗色模式 — 自动处理,无需手动覆盖 */
/* 如果需要自定义暗色品牌色 */
.dark {
--vp-c-brand-1: #818cf8;
--vp-c-brand-2: #6366f1;
--vp-c-brand-3: #4f46e5;
}useData() 类型报错
v2 的 useData 返回更多字段,TypeScript 可能需要更新类型声明:
ts
// 如果之前扩展了 PageData 类型,检查是否需要更新
declare module 'vitepress' {
interface PageData {
// v2 新增字段
wordCount?: number
readingTime?: number
}
}