主题
Vitepress 添加 Giscus 评论
简介
Giscus 是基于 GitHub Discussions 的评论系统。
要在你的网站上使用Giscus,首先需要在GitHub上创建一个仓库,并激活该仓库的Discussions功能。一旦完成设置,当访问者在你的网站上留下评论时,这些评论将以Discussions的形式保存在这个特定的GitHub仓库中。
通过访问 Giscus官网 ,你可以根据自己的GitHub仓库情况配置相关参数(例如仓库名称、讨论类别等),并生成一段JavaScript代码。你需要将这段代码嵌入到你的网页或应用程序中。这样,每当有人浏览你的页面时,这段脚本就会自动从你指定的GitHub仓库中获取评论数据,并将其展示在网页上供用户查看和互动。
以上就是 Giscus 的基本原理。
使用前准备
1. 确保你的仓库是公开的
私有仓库,访客将无法查看 discussion,也就无法使用 Giscus。
2. 安装 giscus app
安装完成后是如下界面,如果未安装请点击链接 giscus app 安装
3. 在你的仓库中启用 Discussions 功能
启用也很简单,进入仓库页面,点击顶部菜单中的 Settings > Features,勾选 Discussions 并保存
获取配置
在 giscus 官网 根据选项配置并获取代码
配置好后,生成的代码大概如下:
html
<script src="https://giscus.app/client.js"
data-repo="weizwz/note"
data-repo-id="R_kgDONJt7fQ"
data-category="General"
data-category-id="DIC_kwDONJt7fc4ClDWs"
data-mapping="url"
data-strict="0"
data-reactions-enabled="1"
data-emit-metadata="0"
data-input-position="top"
data-theme="light_tritanopia"
data-lang="zh-CN"
data-loading="lazy"
crossorigin="anonymous"
async>
</script>
修改项目代码
在 Vitepress 中,我们当然会选择使用组件的方式
1. 安装插件 @giscus/vue
sh
pnpm i @giscus/vue
2. 封装组件
根据此目录新建组件 GiscusComment.vue,内容如下:
vue
<template>
<div style="margin-top: 2rem">
<Giscus
id="comments"
:key="route.path"
repo="weizwz/note"
repo-id="R_kgDONJt7fQ"
category="General"
category-id="DIC_kwDONJt7fc4ClDWs"
mapping="pathname"
strict="1"
term="请不吝赐教!"
reactions-enabled="1"
emit-metadata="0"
input-position="top"
lang="zh-CN"
loading="lazy"
:theme="isDark ? 'dark_tritanopia' : 'light_tritanopia'"></Giscus>
</div>
</template>
<script setup>
import Giscus from '@giscus/vue'
import { watch } from 'vue'
import { inBrowser, useData, useRoute } from 'vitepress'
const { isDark } = useData()
const route = useRoute()
watch(isDark, (dark) => {
if (!inBrowser) return
const iframe = document.querySelector('giscus-widget')?.shadowRoot?.querySelector('iframe')
iframe?.contentWindow?.postMessage(
{ giscus: { setConfig: { theme: dark ? 'dark_tritanopia' : 'light_tritanopia' } } },
'https://giscus.app'
)
})
</script>
3. 使用组件
利用 Vitepress 的 布局插槽,将此组件插入文章最后面。新建 MyLayout 组件,代码如下:
vue
<script setup lang="ts">
import { useData } from 'vitepress'
import DefaultTheme from 'vitepress/theme'
import GiscusComment from './GiscusComment.vue' // 评论模块
</script>
<template>
<DefaultTheme.Layout>
<template #doc-after>
<GiscusComment />
</template>
</DefaultTheme.Layout>
</template>
然后将 MyLayout 组件注入到全局主题中
js
import DefaultTheme from 'vitepress/theme'
import MyLayout from './MyLayout.vue'
export default {
extends: DefaultTheme,
// 使用注入插槽的包装组件覆盖 Layout
Layout: MyLayout
}
最后
最终效果如下: