跳转到内容

VitePress Giscus 评论系统集成完全指南 | 增强网站互动功能

Giscus Comment System

Giscus 是一个基于 GitHub Discussions 的轻量级评论系统,它利用 GitHub 的讨论功能来存储和管理评论。与传统的评论系统相比,Giscus 具有无需数据库、免费托管、支持 Markdown 等优势,非常适合技术博客和文档网站。

为什么选择 Giscus?

Giscus vs 其他评论系统对比

特性GiscusDisqusValineGitalk
数据存储GitHub Discussions第三方服务器LeanCloudGitHub Issues
费用✅ 完全免费💰 付费去广告⚠️ 有限额✅ 免费
隐私保护🔒 优秀⚠️ 追踪用户⚠️ 一般🔒 良好
加载速度⚡⚡⚡ 快🐌 较慢⚡⚡ 中等⚡⚡ 中等
Moderation✅ GitHub 管理✅ 后台管理⚠️ 有限✅ GitHub 管理
自定义主题✅ 支持⚠️ 有限⚠️ 有限⚠️ 有限
国内访问⚠️ 需代理❌ 被墙✅ 快速⚠️ 需代理

Giscus 的核心优势

  1. 零成本:利用 GitHub 基础设施,无需额外服务器
  2. 数据安全:评论存储在 GitHub,自动备份
  3. SEO 友好:评论内容可被搜索引擎索引
  4. Markdown 支持:完整的 Markdown 语法支持
  5. 主题定制:支持浅色/深色主题自动切换
  6. 国际化:支持多语言界面

安装

sh
npm i vitepress-plugin-comment-with-giscus
sh
pnpm i vitepress-plugin-comment-with-giscus
sh
yarn add vitepress-plugin-comment-with-giscus

依赖说明

bash
# 核心依赖
vitepress-plugin-comment-with-giscus  # Giscus 插件

# peer dependencies(自动安装)
vue                                   # Vue 3
vitepress                             # VitePress

创建 index 文件

.vitepress/theme 下创建index.js 或者index.ts文件

项目结构

docs/
├── .vitepress/
│   ├── config.js          # VitePress 配置
│   └── theme/
│       ├── index.js       # 主题入口文件
│       └── Layout.vue     # 可选:自定义布局
├── index.md
└── guide/
    └── introduction.md

配置 index.ts

giscus.ts
ts
// .vitepress/theme/index.js
import { useData, useRoute } from 'vitepress'
import giscusTalk from 'vitepress-plugin-comment-with-giscus'
import DefaultTheme from 'vitepress/theme'

export default {
  ...DefaultTheme,
  enhanceApp(ctx) {
    DefaultTheme.enhanceApp(ctx)
    // ...
  },
  setup() {
    // 获取前言和路由
    const { frontmatter } = useData()
    const route = useRoute()

    // 评论组件 - https://giscus.app/
    giscusTalk(
      {
        repo: 'xxxxxx/xxxxxx', //仓库地址
        repoId: 'xxxxxx', //仓库ID
        category: 'General', // 默认: `General`
        categoryId: 'xxxxxx', //分类ID
        mapping: 'title', // 默认: `pathname`
        strict: '0',
        reactionsEnabled: '0',
        emitMetadata: '0',
        inputPosition: 'top', // 默认: `top`
        lang: 'zh-CN' // 默认: `zh-CN`
      },
      {
        frontmatter,
        route
      }
    )
  }
}

完整配置示例

typescript
// .vitepress/theme/index.ts
import DefaultTheme from 'vitepress/theme'
import { useRoute } from 'vitepress'
import { watch } from 'vue'
import giscusTalk from 'vitepress-plugin-comment-with-giscus'

export default {
  ...DefaultTheme,
  setup() {
    // 获取路由
    const route = useRoute()
    
    // 配置 Giscus
    giscusTalk({
      repo: 'your-username/your-repo',           // GitHub 仓库
      repoId: 'R_kgDOxxxxxx',                     // 仓库 ID
      category: 'General',                        // 讨论分类
      categoryId: 'DIC_xxxxxx',                   // 分类 ID
      mapping: 'pathname',                        // 映射方式
      strict: '0',                                // 严格模式
      reactionsEnabled: '1',                      // 启用表情回应
      emitMetadata: '0',                          // 发送元数据
      inputPosition: 'bottom',                    // 输入框位置
      theme: 'light',                             // 主题
      lang: 'zh-CN',                              // 语言
      loading: 'lazy'                             // 加载方式
    }, {
      frontmatter: route.data?.frontmatter,       // 获取 frontmatter
    })
    
    // 监听路由变化,重新加载评论
    watch(
      () => route.path,
      () => {
        // 路由变化时刷新评论
      }
    )
  }
}

配置参数详解

必需参数

参数说明获取方式
repoGitHub 仓库地址用户名/仓库名
repoId仓库 IDGiscus 工具生成
category讨论分类名称手动创建
categoryId分类 IDGiscus 工具生成

可选参数

参数默认值说明
mappingpathname页面与讨论的映射方式
strict0严格匹配 URL
reactionsEnabled1是否显示表情回应
emitMetadata0是否发送元数据
inputPositionbottom输入框位置(top/bottom)
themelight主题样式
langen界面语言
loadinglazy加载方式(lazy/eager)

giscus 获取参数

giscus 配置获取

详细配置步骤

步骤 1:启用 GitHub Discussions

  1. 进入你的 GitHub 仓库
  2. 点击【Settings】标签
  3. 找到【Features】区域
  4. 勾选【Discussions】复选框
  5. 点击【Save changes】

步骤 2:创建讨论分类

  1. 在仓库中点击【Discussions】标签
  2. 点击【New category】
  3. 填写分类信息:
    • Name: Comments(或任意名称)
    • Description: 用于存储文章评论
    • Emoji: 选择一个表情
  4. 点击【Create category】

步骤 3:获取配置参数

  1. 访问 giscus.app
  2. 填写配置表单:
    • 仓库:选择你的仓库
    • Discussion 分类:选择刚创建的分类
    • Discussion 映射方式:推荐 pathname
    • 功能选项:根据需要勾选
  3. 向下滚动,复制生成的配置代码

配置示例:

javascript
{
  repo: "username/repo",
  repoId: "R_kgDOHxxxxx",
  category: "Comments",
  categoryId: "DIC_kwDOHxxxxx",
  mapping: "pathname",
  strict: "0",
  reactionsEnabled: "1",
  emitMetadata: "0",
  inputPosition: "bottom",
  theme: "light",
  lang: "zh-CN",
  loading: "lazy"
}

步骤 4:测试配置

在本地启动 VitePress:

bash
npm run docs:dev

访问任意页面,应该能看到 Giscus 评论框。

拓展使用

如果文章前言添加以下代码,则不会生成评论区

md
---
comment: false
---

高级用法

1. 按页面禁用评论

markdown
---
title: 隐私政策
comment: false  # 禁用评论
---

# 隐私政策

本文档不需要评论功能。

2. 条件性显示评论

typescript
// .vitepress/theme/index.ts
import { computed } from 'vue'

setup() {
  const route = useRoute()
  
  // 根据路径条件性启用评论
  const enableComment = computed(() => {
    // 排除特定页面
    const excludedPaths = ['/about', '/privacy', '/terms']
    return !excludedPaths.includes(route.path)
  })
  
  if (enableComment.value) {
    giscusTalk({...}, {...})
  }
}

3. 自定义主题切换

typescript
// 监听系统主题变化
import { useData } from 'vitepress'

setup() {
  const { isDark } = useData()
  const route = useRoute()
  
  watch(
    isDark,
    (newValue) => {
      // 动态切换 Giscus 主题
      const iframe = document.querySelector('iframe.giscus-frame')
      if (iframe) {
        iframe.contentWindow.postMessage(
          {
            giscus: {
              setConfig: {
                theme: newValue ? 'dark' : 'light'
              }
            }
          },
          'https://giscus.app'
        )
      }
    }
  )
  
  giscusTalk({
    theme: isDark.value ? 'dark' : 'light',
    // ... 其他配置
  }, {
    frontmatter: route.data?.frontmatter,
  })
}

4. 多语言支持

typescript
// 根据当前语言切换 Giscus 界面语言
import { useData } from 'vitepress'

setup() {
  const { lang } = useData()
  const route = useRoute()
  
  giscusTalk({
    lang: lang.value === 'zh-CN' ? 'zh-CN' : 'en',
    // ... 其他配置
  }, {
    frontmatter: route.data?.frontmatter,
  })
}

主题定制

内置主题

Giscus 提供多种内置主题:

typescript
// 浅色主题
theme: 'light'
theme: 'light_high_contrast'
theme: 'light_protanopia'
theme: 'light_tritanopia'

// 深色主题
theme: 'dark'
theme: 'dark_high_contrast'
theme: 'dark_protanopia'
theme: 'dark_tritanopia'

// 透明主题(适配网站背景)
theme: 'transparent_dark'

// 自定义主题
theme: 'https://example.com/custom.css'

自定义 CSS

css
/* .vitepress/theme/custom.css */

/* 调整评论框样式 */
.giscus {
  max-width: 800px;
  margin: 0 auto;
}

/* 隐藏某些元素 */
.giscus-header {
  display: none;
}

/* 自定义按钮样式 */
.giscus-reaction-button {
  border-radius: 8px;
}

权限管理

评论权限控制

typescript
giscusTalk({
  // 仅允许仓库协作者评论
  strict: '1',
  
  // 或允许所有 GitHub 用户
  strict: '0',
  
  // 需要登录才能评论
  // (由 Giscus 自动处理)
}, {})

内容审核

  1. GitHub Discussions 管理

    • 进入仓库的 Discussions 标签
    • 可以删除、编辑、锁定讨论
    • 可以屏蔽用户
  2. 自动化审核

    yaml
    # .github/workflows/moderate-comments.yml
    name: Moderate Comments
    
    on:
      discussion_comment:
        types: [created]
    
    jobs:
      moderate:
        runs-on: ubuntu-latest
        steps:
          - name: Check for spam
            uses: actions/github-script@v6
            with:
              script: |
                const comment = context.payload.comment.body
                if (comment.includes('spam keyword')) {
                  await github.rest.discussions.deleteComment({
                    owner: context.repo.owner,
                    repo: context.repo.repo,
                    comment_id: context.payload.comment.id
                  })
                }

性能优化

1. 懒加载

typescript
giscusTalk({
  loading: 'lazy',  // 滚动到可视区域才加载
}, {})

2. 预加载策略

typescript
// 在用户可能查看评论时预加载
import { onMounted } from 'vue'

onMounted(() => {
  // 监听滚动事件
  window.addEventListener('scroll', () => {
    const commentSection = document.querySelector('.giscus')
    if (commentSection && isInViewport(commentSection)) {
      // 触发加载
      commentSection.scrollIntoView({ behavior: 'smooth' })
    }
  })
})

3. CDN 加速

html
<!-- 在 index.html 中添加 -->
<link rel="preconnect" href="https://giscus.app">

常见问题排查

问题 1:评论框不显示

bash
# 检查浏览器控制台错误
# 常见错误及解决方案:

# 错误 1:Invalid repo format
# 解决:确保 repo 格式为 "username/repo"

# 错误 2:Category not found
# 解决:检查 categoryId 是否正确

# 错误 3:Discussions not enabled
# 解决:在仓库设置中启用 Discussions

问题 2:评论无法提交

bash
# 原因 1:未登录 GitHub
# 解决:点击右上角登录按钮

# 原因 2:权限不足
# 解决:检查仓库是否为公开,或邀请用户为协作者

# 原因 3:网络问题
# 解决:检查是否能访问 giscus.app

问题 3:主题不跟随系统

typescript
// 确保正确监听主题变化
import { useData } from 'vitepress'

const { isDark } = useData()

watch(isDark, (newVal) => {
  // 更新主题
  updateGiscusTheme(newVal ? 'dark' : 'light')
})

问题 4:评论重复显示

typescript
// 确保只在 setup 中调用一次
// 不要在多个组件中重复初始化

// 错误做法 ❌
// 在 Layout.vue 和 index.ts 中都调用 giscusTalk

// 正确做法 ✅
// 仅在 index.ts 的 setup 中调用一次

最佳实践

✅ 推荐做法

  1. 使用专用仓库:为评论创建独立的仓库
  2. 定期备份:导出 GitHub Discussions 数据
  3. 设置通知:开启新评论邮件通知
  4. ** moderation**:定期检查和处理垃圾评论
  5. 性能监控:关注 Giscus 加载时间

❌ 避免做法

  1. ❌ 在私有仓库中使用(访问受限)
  2. ❌ 忽略错误日志
  3. ❌ 在生产环境使用调试配置
  4. ❌ 不设置内容审核机制

总结

Giscus 为 VitePress 网站提供了强大的评论功能:

  1. 零成本:完全免费,无需服务器
  2. 易集成:简单配置即可使用
  3. 功能强:支持 Markdown、表情、主题切换
  4. 安全可靠:依托 GitHub 基础设施
  5. SEO 友好:评论内容可被索引

关键配置回顾:

typescript
1. 安装插件:pnpm i vitepress-plugin-comment-with-giscus
2. 启用 GitHub Discussions
3. 获取 repo、repoId、category、categoryId
4. 在 theme/index.ts 中配置
5. 按需禁用特定页面评论

下一步学习:

为你的 VitePress 网站添加互动评论,让知识交流更便捷!💬✨