从 v1 升级到 v2
本指南帮助你从 @fuxishi/vitepress-theme v1.x(基于 VitePress 1.x)平滑迁移到 v2.x(基于 VitePress 2.0)。
前置条件
- VitePress 升级到
2.0+ - Node.js
>=18
bash
npm install vitepress@latest破坏性变更
1. 配置 API 更新
v2 使用 defineConfig<ThemeConfig>() 替代已废弃的 defineConfigWithTheme,并通过交叉类型组合自定义配置。
v1 写法(已废弃):
ts
import { defineConfigWithTheme } from "vitepress"
import fxConfig from "@fuxishi/vitepress-theme/config"
import type { FxThemeConfig } from "@fuxishi/vitepress-theme/config"
export default defineConfigWithTheme<FxThemeConfig>({
extends: fxConfig,
// ...
})v2 写法:
ts
import { defineConfig } from "vitepress"
import type { DefaultTheme } from "vitepress"
import fxConfig from "@fuxishi/vitepress-theme/config"
import type { FxThemeCustomConfig } from "@fuxishi/vitepress-theme"
type ThemeConfig = DefaultTheme.Config & FxThemeCustomConfig
export default defineConfig<ThemeConfig>({
extends: fxConfig,
// ...
})主要变化:
| 项目 | v1 | v2 |
|---|---|---|
| 配置函数 | defineConfigWithTheme | defineConfig<ThemeConfig>() |
| 类型导入 | FxThemeConfig from .../config | FxThemeCustomConfig from @fuxishi/vitepress-theme |
| 类型组合 | 直接继承 DefaultTheme.Config | DefaultTheme.Config & FxThemeCustomConfig |
| 额外导入 | 无 | 需导入 DefaultTheme |
2. 主题注册(无变化)
主题注册方式不变:
ts
import FxTheme from "@fuxishi/vitepress-theme"
import "@fuxishi/vitepress-theme/style.css"
export default FxTheme3. 代码块光束边框增强
v2 中暗色模式的代码块光束边框效果现在也支持代码组(::: code-group)整体容器,hover 时整个代码组展示光束旋转边框。
迁移步骤
步骤 1:升级依赖
bash
npm install @fuxishi/vitepress-theme@latest
npm install vitepress@latest步骤 2:更新配置文件
修改 .vitepress/config.mts,按上方 v2 写法 替换配置导入和函数调用。
完整示例:
ts
import { defineConfig } from "vitepress"
import type { DefaultTheme } from "vitepress"
import fxConfig from "@fuxishi/vitepress-theme/config"
import type { FxThemeCustomConfig } from "@fuxishi/vitepress-theme"
type ThemeConfig = DefaultTheme.Config & FxThemeCustomConfig
export default defineConfig<ThemeConfig>({
extends: fxConfig,
lang: "zh-CN",
title: "我的文档站",
themeConfig: {
// 你原有的配置保持不变
nav: [{ text: "指南", link: "/guide/" }],
sidebar: {
"/guide/": [{ text: "快速开始", link: "/guide/" }],
},
// 以下配置项与 v1 完全兼容,无需修改
musicBall: { enable: true, src: "/music/song.mp3" },
confetti: true,
heroImageColor: true,
smoothScroll: true,
codeBlockFold: { lines: 10 },
},
})步骤 3:验证
启动开发服务器确认一切正常:
bash
npx vitepress dev无需修改的部分
以下配置和行为在 v2 中完全兼容,无需任何改动:
- 主题注册 —
import FxTheme+import "style.css"不变 - 音乐球配置 —
musicBall所有字段不变 - 彩纸效果配置 —
confetti所有模式不变 - Hero 图片取色 —
heroImageColor行为不变 - 平滑滚动 —
smoothScroll行为不变 - 代码块折叠 —
codeBlockFold所有字段不变 - CSS 变量覆盖 — 所有
--fx-beam-c1、--fx-beam-c2、音乐球变量等不变 - 自定义 CSS — 所有自定义样式不变
常见问题
TypeScript 报类型错误
确保 tsconfig.json 包含正确的 VitePress 路径配置,并且使用了 type ThemeConfig = DefaultTheme.Config & FxThemeCustomConfig 交叉类型,而不是 FxThemeConfig extends DefaultTheme.Config。
defineConfigWithTheme 不存在
VitePress 2.0 已废弃 defineConfigWithTheme,请改用 defineConfig<ThemeConfig>()。
NoInfer 报错
NoInfer 是 TypeScript 5.4+ 内置工具类型,不需要从 vitepress 导入。如果遇到此错误,请升级 TypeScript 到 5.4 以上。
