Skip to main content

如何基于 Docusaurus 实现一个托管在 GitHub 上的个人技术博客,并且实现自动化部署到 Vercel

目录


前置准备

需要的账号

  1. GitHub 账号 - https://github.com
  2. Vercel 账号 - https://vercel.com(可用 GitHub 登录)

需要的工具

# 检查 Node.js 版本(需要 >= 18.0)
node -v

# 检查 npm 版本
npm -v

# 检查 Git 版本
git --version

如果未安装,请先安装:


第一步:创建 Docusaurus 项目

1.1 创建项目

打开终端,执行以下命令:

# 使用 npx 创建项目(推荐)
npx create-docusaurus@latest my-blog classic

# 或使用 npm
npm init docusaurus@latest my-blog classic

# 或使用 yarn
yarn create docusaurus my-blog classic

这会创建一个名为 my-blog 的项目,使用 classic 模板。

1.2 启动本地开发

# 进入项目目录
cd my-blog

# 安装依赖(如果还没安装)
npm install

# 启动开发服务器
npm start

浏览器会自动打开 http://localhost:3000,你应该能看到默认的 Docusaurus 网站。

1.3 项目结构预览

my-blog/
├── blog/ # 博客文章目录
│ ├── 2021-08-26-welcome/
│ │ └── index.md
│ ├── 2021-08-01-mdx.md
│ └── authors.yml # 作者信息
├── docs/ # 文档目录(可选)
├── src/
│ ├── components/ # 自定义组件
│ ├── css/
│ │ └── custom.css # 自定义样式
│ └── pages/
│ └── index.js # 首页
├── static/ # 静态资源
│ └── img/
├── docusaurus.config.js # 核心配置文件
├── sidebars.js # 侧边栏配置
├── package.json
└── .gitignore

第二步:配置博客

2.1 修改基本信息

编辑 docusaurus.config.js

// @ts-check
const {themes} = require('prism-react-renderer');

/** @type {import('@docusaurus/types').Config} */
const config = {
// 网站基本信息
title: '我的技术博客',
tagline: '分享编程技术与学习心得',
favicon: 'img/favicon.ico',

// 重要:先设置为临时 URL,部署后再更新
url: 'https://your-site.vercel.app',
baseUrl: '/',

// GitHub 信息(用于编辑链接)
organizationName: 'your-github-username', // 你的 GitHub 用户名
projectName: 'my-blog', // 仓库名

onBrokenLinks: 'throw',
onBrokenMarkdownLinks: 'warn',

// 国际化配置
i18n: {
defaultLocale: 'zh-CN',
locales: ['zh-CN'],
},

presets: [
[
'classic',
/** @type {import('@docusaurus/preset-classic').Options} */
({
docs: false, // 如果只做博客,可以禁用文档功能
blog: {
routeBasePath: '/', // 让博客作为首页
showReadingTime: true,
blogTitle: '我的技术博客',
blogDescription: '分享编程技术与学习心得',
postsPerPage: 10,
blogSidebarTitle: '最近文章',
blogSidebarCount: 'ALL',
feedOptions: {
type: 'all',
copyright: `Copyright © ${new Date().getFullYear()} 我的博客`,
},
// 编辑链接
editUrl: 'https://github.com/your-github-username/my-blog/tree/main/',
},
theme: {
customCss: './src/css/custom.css',
},
}),
],
],

themeConfig:
/** @type {import('@docusaurus/preset-classic').ThemeConfig} */
({
// SEO 元数据
image: 'img/social-card.jpg',
metadata: [
{name: 'keywords', content: '技术博客, 编程, JavaScript, React'},
{name: 'author', content: '你的名字'},
],

// 导航栏
navbar: {
title: '我的技术博客',
logo: {
alt: 'Logo',
src: 'img/logo.svg',
},
items: [
{to: '/', label: '博客', position: 'left'},
{to: '/archive', label: '归档', position: 'left'},
{to: '/tags', label: '标签', position: 'left'},
{
href: 'https://github.com/your-github-username',
label: 'GitHub',
position: 'right',
},
],
},

// 页脚
footer: {
style: 'dark',
links: [
{
title: '博客',
items: [
{
label: '最新文章',
to: '/',
},
{
label: '标签',
to: '/tags',
},
],
},
{
title: '社交',
items: [
{
label: 'GitHub',
href: 'https://github.com/your-github-username',
},
{
label: 'Twitter',
href: 'https://twitter.com/your-twitter',
},
],
},
{
title: '更多',
items: [
{
label: '关于',
to: '/about',
},
{
label: 'RSS',
href: '/blog/rss.xml',
},
],
},
],
copyright: `Copyright © ${new Date().getFullYear()} 我的技术博客. Built with Docusaurus.`,
},

// 代码高亮主题
prism: {
theme: themes.github,
darkTheme: themes.dracula,
additionalLanguages: ['bash', 'json', 'java', 'python'],
},

// 色彩模式
colorMode: {
defaultMode: 'light',
disableSwitch: false,
respectPrefersColorScheme: true,
},
}),
};

module.exports = config;

2.2 配置作者信息

编辑 blog/authors.yml

your_name:
name: 你的名字
title: 前端工程师
url: https://github.com/your-github-username
image_url: https://github.com/your-github-username.png
email: your-email@example.com
page: true

# 可以添加多个作者
another_author:
name: 其他作者
title: 软件工程师
url: https://github.com/another-username
image_url: https://github.com/another-username.png

2.3 自定义样式

编辑 src/css/custom.css

/**
* 自定义颜色主题
*/
:root {
/* 主色调 */
--ifm-color-primary: #2e8555;
--ifm-color-primary-dark: #29784c;
--ifm-color-primary-darker: #277148;
--ifm-color-primary-darkest: #205d3b;
--ifm-color-primary-light: #33925d;
--ifm-color-primary-lighter: #359962;
--ifm-color-primary-lightest: #3cad6e;

/* 字体 */
--ifm-font-family-base: 'Arial', 'Microsoft YaHei', '微软雅黑', sans-serif;
--ifm-code-font-size: 95%;

/* 其他 */
--docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.1);
}

/* 暗色模式 */
[data-theme='dark'] {
--ifm-color-primary: #25c2a0;
--ifm-color-primary-dark: #21af90;
--ifm-color-primary-darker: #1fa588;
--ifm-color-primary-darkest: #1a8870;
--ifm-color-primary-light: #29d5b0;
--ifm-color-primary-lighter: #32d8b4;
--ifm-color-primary-lightest: #4fddbf;
--docusaurus-highlighted-code-line-bg: rgba(0, 0, 0, 0.3);
}

/* 自定义样式 */
.hero__title {
font-size: 3rem;
}

.markdown h1 {
font-size: 2.5rem;
}

/* 代码块样式 */
.prism-code {
font-size: 0.9rem;
line-height: 1.5;
}

第三步:推送到 GitHub

3.1 初始化 Git 仓库

# 初始化 Git(如果还没有)
git init

# 查看 .gitignore 是否已正确配置
cat .gitignore

确保 .gitignore 包含:

# Dependencies
node_modules/
.pnp
.pnp.js

# Production
/build
.docusaurus
.cache-loader

# Misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*

3.2 创建 GitHub 仓库

  1. 访问 https://github.com/new
  2. 仓库名称:my-blog(或其他名字)
  3. 选择 Public(公开仓库)
  4. 不要勾选 "Initialize this repository with a README"
  5. 点击 "Create repository"

3.3 推送代码

# 添加所有文件
git add .

# 提交
git commit -m "Initial commit: Docusaurus blog setup"

# 添加远程仓库(替换为你的 GitHub 用户名和仓库名)
git remote add origin https://github.com/your-github-username/my-blog.git

# 推送到 GitHub
git branch -M main
git push -u origin main

第四步:部署到 Vercel

4.1 连接 GitHub 仓库

  1. 访问 https://vercel.com
  2. 使用 GitHub 账号登录
  3. 点击 "Add New""Project"
  4. 选择 "Import Git Repository"
  5. 找到你的 my-blog 仓库,点击 "Import"

4.2 配置项目

Vercel 会自动检测 Docusaurus 项目,配置如下:

  • Framework Preset: Docusaurus
  • Build Command: npm run build
  • Output Directory: build
  • Install Command: npm install

通常不需要修改,直接点击 "Deploy"

4.3 等待部署

  • 部署过程大约需要 1-3 分钟
  • 部署成功后,Vercel 会生成一个 URL,类似:https://my-blog-xxxx.vercel.app

4.4 配置自定义域名(可选)

  1. 在 Vercel 项目页面,点击 "Settings""Domains"
  2. 添加你的域名(需要先购买域名)
  3. 按照提示配置 DNS 记录

第五步:自定义配置

5.1 更新配置文件中的 URL

部署成功后,更新 docusaurus.config.js

const config = {
// 更新为你的 Vercel URL
url: 'https://my-blog-xxxx.vercel.app',
baseUrl: '/',

// 更新 GitHub 编辑链接
organizationName: 'your-github-username',
projectName: 'my-blog',
};

提交并推送:

git add docusaurus.config.js
git commit -m "Update site URL"
git push

Vercel 会自动检测并重新部署!这就是自动化部署的魅力。

5.2 配置环境变量(可选)

如果需要使用环境变量:

  1. 在 Vercel 项目页面,进入 "Settings""Environment Variables"
  2. 添加变量,如:API_KEY=your_api_key
  3. 在代码中使用:process.env.API_KEY

第六步:编写博客文章

6.1 创建第一篇博客

blog/ 目录创建文件:blog/2025-11-16-first-post.md

---
slug: first-post
title: 我的第一篇博客
authors: your_name
tags: [博客, Docusaurus, 技术]
---

# 欢迎来到我的技术博客

这是我的第一篇博客文章,使用 Docusaurus 构建并部署到 Vercel。

<!--truncate-->

## 为什么选择 Docusaurus?

- 🚀 快速搭建
- 📝 Markdown 写作
- ⚛️ React 驱动
- 🎨 高度可定制

## 接下来的计划

我将在这个博客分享:

1. 前端开发技术
2. JavaScript 深入学习
3. 项目实战经验
4. 学习笔记

敬请期待!

6.2 文章命名规范

Docusaurus 支持多种命名方式:

方式 1:日期格式文件名

blog/2025-11-16-first-post.md
blog/2025-11-17-second-post.mdx

方式 2:文件夹结构

blog/
├── 2025-11-16-my-post/
│ ├── index.md
│ └── image.png

6.3 Front Matter 配置

完整的 Front Matter 选项:

---
slug: my-custom-slug # 自定义 URL 路径
title: 文章标题 # 必填
authors: [your_name, co_author] # 作者(可多个)
tags: [标签1, 标签2] # 标签
date: 2025-11-16T10:00 # 发布日期(可选)
hide_table_of_contents: false # 是否隐藏目录
keywords: [关键词1, 关键词2] # SEO 关键词
description: 文章描述 # SEO 描述
image: ./image.png # 社交分享图片
draft: false # 是否为草稿
---

6.4 提交并推送

git add blog/
git commit -m "Add first blog post"
git push

几分钟后,访问你的 Vercel URL,新文章就会出现!


进阶优化

7.1 添加 Google Analytics

安装插件:

npm install @docusaurus/plugin-google-gtag

配置 docusaurus.config.js

module.exports = {
plugins: [
[
'@docusaurus/plugin-google-gtag',
{
trackingID: 'G-XXXXXXXXXX',
anonymizeIP: true,
},
],
],
};

7.2 添加评论功能(Giscus)

  1. 在 GitHub 仓库启用 Discussions
  2. 访问 https://giscus.app/zh-CN 获取配置
  3. 创建 src/components/GiscusComment.js
import React from 'react';
import Giscus from "@giscus/react";
import { useColorMode } from '@docusaurus/theme-common';

export default function GiscusComment() {
const { colorMode } = useColorMode();

return (
<Giscus
repo="your-username/my-blog"
repoId="your-repo-id"
category="General"
categoryId="your-category-id"
mapping="pathname"
reactionsEnabled="1"
emitMetadata="0"
inputPosition="top"
theme={colorMode}
lang="zh-CN"
loading="lazy"
/>
);
}
  1. 安装依赖:
npm install @giscus/react
  1. 使用 Swizzle 自定义博客文章页面:
npm run swizzle @docusaurus/theme-classic BlogPostItem -- --wrap

在生成的组件中添加评论组件。

7.3 添加 SEO 优化

创建 src/pages/about.js

import React from 'react';
import Layout from '@theme/Layout';

export default function About() {
return (
<Layout
title="关于我"
description="关于我的个人简介">
<div style={{padding: '2rem'}}>
<h1>关于我</h1>
<p>我是一名热爱技术的开发者...</p>
</div>
</Layout>
);
}

7.4 添加 RSS 订阅

RSS 已自动生成,位于:

  • https://your-site.vercel.app/blog/rss.xml
  • https://your-site.vercel.app/blog/atom.xml

在页脚添加链接即可。

7.5 性能优化

docusaurus.config.js 添加:

module.exports = {
future: {
experimental_faster: true,
},

// 启用压缩
webpack: {
jsLoader: (isServer) => ({
loader: require.resolve('swc-loader'),
options: {
jsc: {
parser: {
syntax: 'typescript',
tsx: true,
},
target: 'es2017',
},
module: {
type: isServer ? 'commonjs' : 'es6',
},
},
}),
},
};

自动化部署工作流

自动化流程说明

当你完成上述配置后,工作流程如下:

本地修改 → git push → GitHub 仓库更新 → Vercel 自动检测 → 自动构建部署 → 网站更新

日常发布流程

# 1. 写一篇新文章
vim blog/2025-11-16-new-post.md

# 2. 本地预览
npm start

# 3. 提交到 GitHub
git add .
git commit -m "Add new post: title"
git push

# 4. 等待 1-3 分钟,自动部署完成!

配置部署通知

  1. 在 Vercel 项目设置中,进入 "Git"
  2. 配置 "Deploy Hooks" 可以触发手动部署
  3. 配置 "Notifications" 接收部署通知(邮件、Slack 等)

常见问题

Q1: 部署失败,显示构建错误

解决方案:

# 本地测试构建
npm run build

# 如果本地构建失败,修复错误后再推送
npm run serve # 预览构建结果

Q2: 推送到 GitHub 后 Vercel 没有自动部署

检查清单:

  1. 确认 Vercel 已连接到正确的 GitHub 仓库
  2. 检查 Vercel 项目设置 → Git → Branch,确保监听的是 main 分支
  3. 查看 Vercel 的 Deployments 页面,查看部署日志

Q3: 图片不显示

解决方案:

<!-- 正确:相对于 static/ 目录 -->
![Logo](/img/logo.png)

<!-- 或使用 require -->
import logo from '@site/static/img/logo.png';
<img src={logo} alt="Logo" />

Q4: 修改配置后网站样式错误

解决方案:

# 清除缓存
npm run clear
rm -rf .docusaurus
rm -rf build

# 重新启动
npm start

Q5: 如何回滚到之前的版本?

在 Vercel 中:

  1. 进入项目的 "Deployments" 页面
  2. 找到之前的成功部署
  3. 点击 "..." → "Promote to Production"

在 Git 中:

# 查看提交历史
git log --oneline

# 回滚到指定版本
git revert <commit-hash>
git push

Q6: 如何设置自定义 404 页面?

创建 src/pages/404.js

import React from 'react';
import Layout from '@theme/Layout';

export default function NotFound() {
return (
<Layout title="页面未找到">
<div style={{padding: '2rem', textAlign: 'center'}}>
<h1>404</h1>
<p>抱歉,页面未找到。</p>
<a href="/">返回首页</a>
</div>
</Layout>
);
}

后续扩展建议

1. 内容规划

  • 📅 制定发布计划(每周/每月几篇)
  • 🏷️ 建立标签体系
  • 📂 创建文章系列

2. 功能扩展

  • 添加搜索功能(Algolia DocSearch)
  • 集成邮件订阅
  • 添加深色模式切换动画
  • 创建作品集页面

3. SEO 优化

  • 提交站点地图到 Google Search Console
  • 优化文章元数据
  • 添加结构化数据(JSON-LD)
  • 配置社交分享卡片

4. 性能监控

  • 使用 Vercel Analytics
  • 配置 Web Vitals 监控
  • 定期检查页面加载速度

总结

🎉 恭喜!你已经成功:

✅ 创建了基于 Docusaurus 的技术博客
✅ 托管代码到 GitHub
✅ 实现自动化部署到 Vercel
✅ 掌握了博客写作和发布流程

核心优势:

  • 🚀 每次 git push 即自动部署
  • 💰 完全免费(GitHub + Vercel 免费套餐)
  • 🌍 全球 CDN 加速
  • 📱 响应式设计,移动端友好
  • ⚡ 极致性能,SSG 静态生成

现在开始你的创作之旅吧! ✍️


参考资源


最后更新时间:2025年11月16日