Skip to content

调试与排错

本文档汇总了 VitePress 开发过程中常见的问题、错误信息和解决方案,帮助你快速定位和解决问题。

开发环境调试

使用浏览器 DevTools

VitePress 基于 Vue 3,可以充分利用浏览器开发者工具:

1. Vue DevTools

安装 Vue DevTools 浏览器扩展:

bash
# 支持 Chrome、Firefox、Edge
# 在扩展商店搜索 "Vue.js devtools" 安装

功能包括:

  • 查看组件树结构
  • 检查组件 props、data、computed
  • 追踪事件和 Pinia 状态
  • 性能分析

2. Chrome DevTools 技巧

javascript
// 在控制台中使用 VitePress API
import { useData } from 'vitepress'
const { page, frontmatter } = useData()

// 查看 frontmatter 数据
console.log(frontmatter.value)

控制台输出调试

在 Vue 组件中添加调试信息:

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

const data = ref(null)

onMounted(() => {
  console.log('组件已挂载')
  console.log('数据:', data.value)
  
  // 使用 debugger 设置断点
  // debugger
})
</script>

Vite 调试模式

启动开发服务器时开启调试:

bash
# 启用 Vite 调试日志
DEBUG=vite:* npm run docs:dev

# 只看特定模块
DEBUG=vite:config npm run docs:dev

常见错误速查表

按错误关键词快速定位问题:

错误关键词常见原因解决方案
Port XXXX is in use端口被占用更改端口或终止占用进程
Cannot find module依赖缺失/路径错误npm install / 检查路径
heap out of memoryNode.js 内存不足增加 --max-old-space-size
Failed to resolve component组件未注册全局注册或局部导入
Unexpected token语法错误/ESM/CJS 冲突检查 type: "module"
Hydration mismatchSSR/客户端渲染不一致检查条件渲染和浏览器 API
ENOENT: no such file文件路径错误检查路径大小写和扩展名
Circular dependency循环依赖重构导入结构
CSS variable not foundCSS 变量名错误检查 v2 变量重命名
404 Not Found路由/路径错误检查 base 配置和文件位置
EISDIR路径指向目录检查文件路径是否指向文件
shiki highlight代码语言标识错误使用正确的语言标识符
peerDependencies版本不兼容检查插件与 VitePress 版本
Mixed contentHTTPS 页面加载 HTTP 资源使用协议相对 URL

常见错误及解决方案

1. 端口占用

错误信息:

text
Port 5173 is in use, trying another one...

解决方案:

ts
// docs/.vitepress/config.mts
export default defineConfig({
  vite: {
    server: {
      port: 3000,  // 更改端口
      strictPort: true  // 端口被占用时报错而不是尝试下一个
    }
  }
})

或使用命令行:

bash
# 查找占用端口的进程
lsof -i :5173

# 终止进程
kill -9 <PID>

2. 模块未找到

错误信息:

text
Cannot find module 'xxx' or its corresponding type declarations

解决方案:

bash
# 1. 检查是否安装依赖
npm ls xxx

# 2. 重新安装
npm install xxx

# 3. 清除缓存后重装
rm -rf node_modules package-lock.json
npm install

3. 内存溢出

错误信息:

text
JavaScript heap out of memory

解决方案:

bash
# 增加内存限制
NODE_OPTIONS="--max-old-space-size=8192" npm run docs:build

# 或在 package.json 中配置
{
  "scripts": {
    "build": "NODE_OPTIONS='--max-old-space-size=8192' vitepress build docs"
  }
}

优化建议:

  • 减少页面数量
  • 优化图片资源
  • 检查是否有循环依赖

4. 热更新不工作

问题: 修改文件后页面不自动刷新

解决方案:

ts
// docs/.vitepress/config.mts
export default defineConfig({
  vite: {
    server: {
      watch: {
        usePolling: true  // 在某些系统上需要轮询
      }
    }
  }
})

检查文件排除:

ts
export default defineConfig({
  srcExclude: ['README.md'],  // 确保文件没有被排除
})

5. 样式不生效

问题: CSS 样式未应用或被覆盖

解决方案:

vue
<style scoped>
/* 使用 scoped 避免样式污染 */
.custom-class {
  color: red;
}
</style>

<style>
/* 全局样式放在非 scoped 块中 */
:root {
  --vp-c-brand-1: #6366f1;
}
</style>

检查 CSS 优先级:

css
/* 使用 !important(最后手段) */
.my-style {
  color: red !important;
}

/* 或使用更具体的选择器 */
.custom-container .my-style {
  color: red;
}

6. 构建失败

错误信息:

text
Build failed with errors

排查步骤:

bash
# 1. 清除缓存
rm -rf docs/.vitepress/cache
rm -rf docs/.vitepress/dist

# 2. 检查 Markdown 语法
# 确保没有未闭合的标签或语法错误

# 3. 详细日志模式
DEBUG=* npm run docs:build 2>&1 | tee build.log

7. 图片加载失败

问题: 图片显示为 404

解决方案:

markdown
<!-- 正确的图片路径 -->
![Logo](/logo.svg)  <!-- public 目录 -->

![Screenshot](./images/screenshot.png)  <!-- 相对路径 -->

检查 public 目录结构:

text
docs/
├── public/
│   └── logo.svg  ✅ 通过 /logo.svg 访问
├── images/
│   └── screenshot.png  ✅ 通过相对路径访问

8. 组件注册失败

错误信息:

text
Failed to resolve component: XxxComponent

解决方案:

ts
// docs/.vitepress/theme/index.ts
import DefaultTheme from 'vitepress/theme'
import MyComponent from './components/MyComponent.vue'

export default {
  extends: DefaultTheme,
  enhanceApp({ app }) {
    // 全局注册组件
    app.component('MyComponent', MyComponent)
  }
}

或在 Markdown 中局部导入:

markdown
<script setup>
import MyComponent from './components/MyComponent.vue'
</script>

<MyComponent />

9. TypeScript 类型错误

错误信息:

text
Could not find declaration file for module 'xxx'

解决方案:

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

// 或创建类型声明文件
// docs/types/shims.d.ts
declare module 'xxx' {
  export default function(): void
}

10. Algolia 搜索失败

问题: Algolia 搜索无法工作

解决方案:

ts
// 检查配置是否正确
export default defineConfig({
  themeConfig: {
    search: {
      provider: 'algolia',
      options: {
        appId: 'YOUR_APP_ID',      // 确保正确
        apiKey: 'YOUR_API_KEY',    // 确保正确
        indexName: 'YOUR_INDEX'    // 确保正确
      }
    }
  }
})

验证步骤:

  1. 登录 Algolia 控制台确认凭证
  2. 检查索引是否已创建
  3. 使用浏览器 DevTools 检查网络请求

11. Hydration Mismatch

错误信息:

text
Hydration mismatch: server rendered HTML differs from client

常见原因和解决方案:

vue
<!-- ❌ 错误:SSR 时 window/document 不存在 -->
<script setup>
import { ref } from 'vue'
const width = ref(window.innerWidth) // SSR 报错
</script>

<!-- ✅ 正确:在 onMounted 中使用浏览器 API -->
<script setup>
import { ref, onMounted } from 'vue'
const width = ref(0)
onMounted(() => {
  width.value = window.innerWidth
})
</script>

<!-- ✅ 正确:使用 v-if 保证仅客户端渲染 -->
<ClientOnly>
  <BrowserDependentComponent />
</ClientOnly>

使用 defineClientComponent(v2):

ts
import { defineClientComponent } from 'vitepress'

const MyChart = defineClientComponent(() => import('./MyChart.vue'))

12. ESM / CommonJS 冲突

错误信息:

text
require() of ES Module not supported

解决方案:

json
// package.json
{
  "type": "module"
}
ts
// 使用 ESM 导入替代 require
// ❌ const plugin = require('vitepress-plugin-xxx')
// ✅ import { plugin } from 'vitepress-plugin-xxx'

13. VitePress v2 CSS 变量不生效

问题: 升级到 v2 后自定义颜色失效

解决方案:

css
/* v1 的变量名在 v2 中已废弃 */
/* ❌ */ --vp-c-brand
/* ✅ */ --vp-c-brand-1

/* ❌ */ --vp-c-text
/* ✅ */ --vp-c-text-1

/* ❌ */ --vp-c-text-light
/* ✅ */ --vp-c-text-2

14. 构建时 Markdown 解析错误

错误信息:

text
[vitepress] Error parsing markdown: ...

常见原因:

  • 未闭合的代码块
  • HTML 标签未正确闭合
  • 在代码块中嵌套代码围栏
markdown
<!-- ❌ 嵌套代码围栏未正确转义 -->
```js
```vue  <!-- 内层未转义 -->
<template>...</template>

<!-- ✅ 使用更多反引号包裹 -->
````markdown
```vue
<template>...</template>
```

### 15. 侧边栏/导航栏不显示

**常见原因:**

| 原因 | 检查方式 |
|------|---------|
| 路径不匹配 | sidebar key 必须以 `/` 开头和结尾 |
| 文件扩展名 | link 不需要 `.md` 扩展名 |
| `srcExclude` | 文件可能被排除了 |
| `cleanUrls` | URL 格式与配置不匹配 |

```ts
// ✅ 正确的侧边栏路径
sidebar: {
  '/guide/': [...]  // 以 / 结尾
}

// ✅ 正确的链接
{ text: '介绍', link: '/guide/intro' }  // 不含 .md
```

### 16. 搜索功能异常

**问题分类:**

| 问题 | 原因 | 解决方案 |
|------|------|---------|
| 本地搜索无结果 | 页面被 `srcExclude` 排除 | 检查 `srcExclude` 配置 |
| 本地搜索无结果 | 页面有 `search: false` | 检查 frontmatter |
| Algolia 配置报错 | v2 格式变更 | 使用 `themeConfig.search` |
| 搜索结果不完整 | 索引未更新 | 重新构建或重新爬取 |

```yaml
# 禁用特定页面的搜索
---
search: false
---
```

### 17. 静态资源 404

**常见场景:**

| 场景 | 正确路径 | 说明 |
|------|---------|------|
| `public/` 下的文件 | `/logo.svg` | 以 `/` 开头 |
| 相对路径引用 | `./image.png` | 相对于当前 `.md` 文件 |
| `base` 配置 | `withBase('/logo.svg')` | 子路径部署 |
| npm 包中的资源 | `import xxx from 'pkg'` | 需要构建工具处理 |

```ts
// 子路径部署时使用 withBase
import { withBase } from 'vitepress'
const logoUrl = withBase('/logo.svg')
```

## 构建问题排查

### 详细构建日志

```bash
# 启用详细日志
npm run docs:build -- --debug

# 或使用环境变量
VITE_DEBUG=true npm run docs:build
```

### 检查构建产物

```bash
# 构建后检查产物
ls -la docs/.vitepress/dist

# 检查特定文件
cat docs/.vitepress/dist/index.html
```

### 预览构建结果

```bash
# 本地预览构建产物
npm run docs:preview

# 指定端口
npm run docs:preview -- --port 4173
```

## 性能问题调试

### 分析包体积

```bash
# 安装分析工具
npm add -D rollup-plugin-visualizer

# 配置
```

```ts
// docs/.vitepress/config.mts
import { visualizer } from 'rollup-plugin-visualizer'

export default defineConfig({
  vite: {
    build: {
      rollupOptions: {
        plugins: [
          visualizer({
            open: true,
            filename: 'dist/stats.html'
          })
        ]
      }
    }
  }
})
```

### 分析开发服务器性能

```bash
# 使用 Vite 插件检查
npm add -D vite-plugin-inspect
```

```ts
import Inspect from 'vite-plugin-inspect'

export default defineConfig({
  vite: {
    plugins: [Inspect()]
  }
})
```

访问 `http://localhost:5173/__inspect/` 查看详情。

## 常用调试命令

```bash
# 查看依赖树
npm ls

# 检查过期依赖
npm outdated

# 检查安全漏洞
npm audit

# 更新依赖
npm update

# 强制重新构建
rm -rf node_modules/.vite
rm -rf docs/.vitepress/cache
npm run docs:build
```

## 日志调试技巧

### 自定义日志函数

```ts
// docs/.vitepress/utils/debug.ts
const isDev = import.meta.env.DEV

export function debug(...args: any[]) {
  if (isDev) {
    console.log('[Debug]', ...args)
  }
}

export function warn(...args: any[]) {
  console.warn('[Warning]', ...args)
}

export function error(...args: any[]) {
  console.error('[Error]', ...args)
}
```

使用:

```vue
<script setup>
import { debug } from '../utils/debug'

debug('当前数据:', data.value)
</script>
```

### 构建时日志

```ts
// docs/.vitepress/config.mts
export default defineConfig({
  buildEnd(siteConfig) {
    console.log('构建完成!')
    console.log('输出目录:', siteConfig.outDir)
  },
  
  transformHead({ pageData }) {
    console.log('处理页面:', pageData.title)
    return {}
  }
})
```

## 问题排查清单

遇到问题时,按以下顺序检查:

- [ ] 1. 清除缓存 (`rm -rf docs/.vitepress/cache`)
- [ ] 2. 删除 node_modules 重新安装
- [ ] 3. 检查 Node.js 版本 (需要 >= 18)
- [ ] 4. 检查 VitePress 版本 (`npm ls vitepress`)
- [ ] 5. 查看 package.json 依赖冲突
- [ ] 6. 检查 Markdown 语法错误
- [ ] 7. 检查路径是否正确
- [ ] 8. 检查组件是否正确注册
- [ ] 9. 检查配置文件语法
- [ ] 10. 查看完整错误日志

## 获取帮助

如果以上方法都无法解决问题:

1. **搜索 Issues**:[VitePress GitHub Issues](https://github.com/vuejs/vitepress/issues)
2. **社区讨论**:[GitHub Discussions](https://github.com/vuejs/vitepress/discussions)
3. **Discord 社区**:[VitePress Discord](https://discord.gg/HBkdryt)
4. **提交 Issue**:提供完整复现步骤和环境信息

提交 Issue 模板:

```markdown
## 环境信息
- VitePress 版本:
- Node.js 版本:
- 操作系统:
- 包管理器 (npm/yarn/pnpm):

## 复现步骤
1. 
2. 
3. 

## 期望行为


## 实际行为


## 日志/截图

```

## 下一步

学习 [CI/CD 自动化部署](/best-practices/cicd) 来自动化你的构建流程。

贡献者

加载中...

想要成为贡献者?

在 CNB 上参与贡献