前言
作为一个热爱技术折腾的开发者,我总是喜欢尝试各种新奇的工具和框架。最近我发现了一个简洁、能够在 GitHub Pages 上部署的 VitePress 文档系统,决定用它来收集网络上的沙雕乐子。
一般人喜欢用自己电脑进行本地测试,这需要先在电脑上安装 Node.js 等环境,这还会有 Node.js 版本冲突、依赖安装失败、不同项目环境隔离等问题出现,或者没有电脑。
后来我发现了 GitHub Codespaces 于是就想能不能使用它来测试项目呢?于是试了一下,还真可以。
开始
正如标题所说,这是使用 GitHub 的工具部署的,所以需要一个 GitHub 账号,如果没有那就去注册一个。
当你有了 GitHub 账号,就需要准备一个空的仓库了,如果没有那就去创建一个,你可以在个人账户或者组织上创建,如果作为你或者你组织的主页就命名为 <用户名/组织名>.github.io
。
然后就需要创建一个 Codespaces 了,打开仓库,点击 “Code” 按钮,然后点击 “Create Codespace on main” 这个很明显的按钮。
它将自动跳转至一个域名为 <一堆字母和数字>.github.dev
,然后就能看到一个网页版的 VSCode。
安装与配置 VitePress
VSCode 下方有一个终端,直接输入 官网教程 里的命令。
npm add -D vitepress
npx vitepress init
然后它就问了我几个简单的问题,大概就这样:
┌ Welcome to VitePress!
│
◇ Where should VitePress initialize the config?
│ ./docs
│
◇ Where should VitePress look for your markdown files?
│ ./docs
│
◇ Site title:
│ My Awesome Project
│
◇ Site description:
│ A VitePress Site
│
◇ Theme:
│ Default Theme
│
◇ Use TypeScript for config and theme files?
│ Yes
│
◇ Add VitePress npm scripts to package.json?
│ Yes
│
◇ Add a prefix for VitePress npm scripts?
│ Yes
│
◇ Prefix for VitePress npm scripts:
│ docs
│
└ Done! Now run pnpm run docs:dev and start writing.
完成后它自动生成了几个文件夹和几个文件,打开 docs 里面的 .md 文件可以编辑和删除,用 Markdown 编写,也可以创建一些 .md 文件,例如 googol.md
,index.md
是用于调整首页显示的内容的,注意不要把 index.md
删了,docs 文件夹内还有一个名为 .vitepress 的文件夹,这个文件夹是用于更改配置的,里面包含标题、描述、导航栏、侧边栏应该显示的内容。
部署至 GitHub Pages
配置完成后,在侧边栏找到 “源代码管理” 点进去,然后点击 “提交”,直接提交,返回 GitHub 仓库应该就能看到在 Codespaces 所做的更改已经应用到仓库中了。
然后就是用 workflows 部署至 GitHub Pages 了,在项目的 .github/workflows 目录中创建一个名为 deploy.yml 的文件,其中包含这样的内容:
name: Deploy VitePress site to Pages
on:
push:
branches: [main]
workflow_dispatch:
permissions:
contents: read
pages: write
id-token: write
concurrency:
group: pages
cancel-in-progress: false
jobs:
build:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
fetch-depth: 0 # 如果未启用 lastUpdated,则不需要
# - uses: pnpm/action-setup@v3 # 如果使用 pnpm,请取消此区域注释
# with:
# version: 9
# - uses: oven-sh/setup-bun@v1 # 如果使用 Bun,请取消注释
- name: Setup Node
uses: actions/setup-node@v4
with:
node-version: 20
cache: npm # 或 pnpm / yarn
- name: Setup Pages
uses: actions/configure-pages@v4
- name: Install dependencies
run: npm ci # 或 pnpm install / yarn install / bun install
- name: Build with VitePress
run: npm run docs:build # 或 pnpm docs:build / yarn docs:build / bun run docs:build
- name: Upload artifact
uses: actions/upload-pages-artifact@v3
with:
path: docs/.vitepress/dist
deploy:
environment:
name: github-pages
url: ${{ steps.deployment.outputs.page_url }}
needs: build
runs-on: ubuntu-latest
name: Deploy
steps:
- name: Deploy to GitHub Pages
id: deployment
uses: actions/deploy-pages@v4
接着在存储库设置中的“Pages”菜单项下,选择“Build and deployment > Source > GitHub Actions”。
等待一会应该就部署完成了,你应该能看到站点部署到 https://<用户名/组织名>.github.io/[仓库]/ 或 https://<自定义域名>/,这取决于你的设置。
进入站点看效果,这是我的站点 https://lezinote.github.io。