跳轉到內容

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 網站添加互動評論,讓知識交流更便捷!💬✨

最後更新於: