Skip to content

构建优化

了解如何优化 VitePress 的构建过程和输出。

构建配置

基础构建命令

bash
# 开发构建
npm run docs:build

# 带调试信息构建
DEBUG=vitepress:* npm run docs:build

构建配置选项

ts
export default defineConfig({
  // 输出目录
  outDir: '../dist',
  
  // 缓存目录
  cacheDir: '.vitepress/cache',
  
  // 清理输出目录
  cleanUrls: true,
  
  // 传递 Vite 配置
  vite: {
    build: {
      // 目标浏览器
      target: 'esnext',
      
      // 最小化
      minify: 'esbuild',
      
      // 代码分割
      rollupOptions: {
        output: {
          manualChunks: {
            'vendor': ['vue'],
            'theme': ['vitepress']
          }
        }
      },
      
      // 块大小警告限制
      chunkSizeWarningLimit: 1000
    }
  }
})

#--- title: 构建优化 description: 优化 VitePress 的构建过程和输出 tags:

  • 构建
  • 优化 prev: text: 搜索功能 link: /advanced/search next: text: 部署与发布 link: /advanced/deployment

构建优化

减小包体积

ts
export default defineConfig({
  vite: {
    build: {
      // 启用压缩
      minify: 'esbuild',
      
      // CSS 代码分割
      cssCodeSplit: true,
      
      // 移除 console
      esbuild: {
        drop: ['console', 'debugger']
      }
    }
  }
})

代码分割策略

ts
export default defineConfig({
  vite: {
    build: {
      rollupOptions: {
        output: {
          // 自定义代码分割
          manualChunks(id) {
            if (id.includes('node_modules')) {
              if (id.includes('vue')) {
                return 'vue'
              }
              if (id.includes('vitepress')) {
                return 'vitepress'
              }
              return 'vendor'
            }
          }
        }
      }
    }
  }
})

环境变量

定义环境变量

创建 .env 文件:

bash
# .env
VITE_SITE_URL=https://example.com

# .env.production
VITE_API_URL=https://api.example.com

# .env.development
VITE_API_URL=http://localhost:3000

使用环境变量

在配置中:

ts
export default defineConfig({
  title: process.env.VITE_SITE_TITLE || '默认标题'
})

在代码中:

ts
const apiUrl = import.meta.env.VITE_API_URL
const mode = import.meta.env.MODE  // 'development' | 'production'

环境变量类型

创建 env.d.ts

ts
/// <reference types="vite/client" />

interface ImportMetaEnv {
  readonly VITE_API_URL: string
  readonly VITE_SITE_URL: string
}

interface ImportMeta {
  readonly env: ImportMetaEnv
}

构建分析

分析包体积

bash
# 安装分析工具
npm add -D rollup-plugin-visualizer
ts
import { visualizer } from 'rollup-plugin-visualizer'

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

构建日志

ts
export default defineConfig({
  vite: {
    build: {
      // 显示详细日志
      reportCompressedSize: true
    }
  }
})

构建钩子

构建前/后处理

ts
// docs/.vitepress/config.mts
export default defineConfig({
  // 构建完成后的钩子
  transformHead({ assets }) {
    // 添加自定义 head 标签
    return [
      ['meta', { name: 'build-time', content: new Date().toISOString() }]
    ]
  },
  
  transformHtml(code, id, { pageData }) {
    // 转换 HTML
    if (id.endsWith('.html')) {
      // 添加自定义内容
    }
    return code
  },
  
  transformPageData(pageData) {
    // 转换页面数据
    pageData.frontmatter.lastUpdated = new Date().toISOString()
  }
})

性能优化

预渲染优化

VitePress 默认进行静态站点生成(SSG),无需额外配置。

图片优化

ts
export default defineConfig({
  vite: {
    // 使用 vite-plugin-image-optimizer
    plugins: [
      // imageOptimizer()
    ]
  }
})

字体优化

ts
export default defineConfig({
  head: [
    // 预加载关键字体
    ['link', {
      rel: 'preload',
      href: '/fonts/main.woff2',
      as: 'font',
      type: 'font/woff2',
      crossorigin: ''
    }]
  ]
})

构建调试

调试模式

bash
# 启用调试日志
DEBUG=vitepress:* npm run docs:build

# 查看构建时间
VITEPRESS_BUILD_ANALYZER=1 npm run docs:build

常见构建问题

内存溢出

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

构建超时

ts
export default defineConfig({
  vite: {
    build: {
      // 增加超时时间
      chunkSizeWarningLimit: 2000
    }
  }
})

缓存问题

bash
# 清除缓存重新构建
rm -rf docs/.vitepress/cache
npm run docs:build

CI/CD 构建

GitHub Actions

yaml
- name: Build
  run: npm run docs:build
  env:
    NODE_OPTIONS: "--max-old-space-size=4096"

构建缓存

yaml
- name: Cache VitePress
  uses: actions/cache@v4
  with:
    path: |
      docs/.vitepress/cache
      docs/.vitepress/dist
    key: vitepress-${{ hashFiles('package-lock.json') }}
    restore-keys: vitepress-

构建检查清单

  • [ ] 配置正确的 base 路径
  • [ ] 启用代码压缩
  • [ ] 配置合理的代码分割
  • [ ] 检查包体积
  • [ ] 配置环境变量
  • [ ] 测试生产构建
  • [ ] 验证所有链接
  • [ ] 检查控制台错误

下一步

学习 运行时 API 了解更多开发技巧。

贡献者

加载中...

想要成为贡献者?

在 CNB 上参与贡献