Skip to content

部署上线

构建站点

sh
npm run docs:build

输出目录:.vitepress/dist/,里面的文件就是完整的静态网站。

本地预览

sh
npm run docs:preview

默认在 http://localhost:4173 启动静态服务器,和线上效果完全一致。可以指定端口:

sh
npm run docs:preview -- --port 8080

设置 base 路径

如果站点部署在子路径(如 https://用户名.github.io/仓库名/),必须设置 base

ts
export default defineConfig({
  base: '/仓库名/',
})

注意base 必须以 / 开头和结尾。

HTTP 缓存配置

如果你能控制服务器的 HTTP 头,建议配置:

Cache-Control: max-age=31536000, immutable

构建产物中所有带哈希的静态资源(JS、CSS、图片)都是不可变的,可以放心让浏览器长期缓存。

部署到 GitHub Pages

1. 创建 GitHub Actions 工作流

创建 .github/workflows/deploy.yml

yaml
name: Deploy VitePress site to Pages

on:
  push:
    branches: [main]

permissions:
  contents: read
  pages: write
  id-token: write

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
        with:
          fetch-depth: 0   # 如果需要 lastUpdated 功能
      - uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm
      - run: npm ci
      - run: npm run docs:build
      - uses: actions/upload-pages-artifact@v3
        with:
          path: .vitepress/dist
      - uses: actions/deploy-pages@v4

2. 在 GitHub 仓库设置

Settings → Pages → Source 选 GitHub Actions

3. 推送代码

sh
git add .
git commit -m "部署文档站点"
git push origin main

每次 push 到 main 分支后 GitHub 会自动构建部署,几分钟后你的站点就在 https://用户名.github.io/仓库名/ 上线了。

如果你用的是 username.github.io 仓库,则站点在 https://用户名.github.io/

部署到 Netlify

  1. 把代码推到 GitHub
  2. 在 Netlify 上 "Import an existing project" 选择那个仓库
  3. 设置:
    • Build command: npm run docs:build
    • Publish directory: .vitepress/dist
  4. 点击 Deploy

Netlify 会自动提供 HTTPS,且支持自定义域名。

部署到 Vercel

  1. 把代码推到 GitHub
  2. 在 Vercel 上导入仓库
  3. 框架会自动检测或手动设置:
    • Build Command: npm run docs:build
    • Output Directory: .vitepress/dist
  4. 如果用了 cleanUrls(去掉 .html 后缀),需要在 vercel.json 中启用:
json
{
  "cleanUrls": true
}

部署到 Cloudflare Pages

  1. 代码推到 GitHub
  2. Cloudflare Pages → 创建项目 → 连接仓库
  3. 构建设置:
    • Build command: npm run docs:build
    • Output directory: .vitepress/dist

Cloudflare Pages 全球 CDN 节点多,国内访问速度比 Netlify/Vercel 快。

其他部署方式

只要是能托管静态文件的平台都能部署 VitePress。只需要:

  • 运行 npm run docs:build
  • .vitepress/dist/ 的内容上传

支持的平台包括但不限于:阿里云 OSS、腾讯云 COS、Nginx 服务器、Docker 容器。

Powered by VitePress