跳到主要内容

Doucsaurus接入评论系统

· 阅读需 3 分钟
zgh
Front-end Engineer

给博客接入评论系统,采用 giscus,原理就是 Github 的 Discussion 评论系统。

1. 配置 giscus

  1. 先去创建一个公开的仓库,可以是单独的仓库,也可以是你博客的源代码仓库
  2. giscus app安装到你的仓库中
  3. 启用 Discussion 功能,在仓库的 Settings -> Features -> Discussions,勾选上即可
  4. 回到 giscus 官网,填上仓库名,如 Ivanzgh/blog-comments
  5. Discussion 分类选择 General
  6. 勾选上「将评论框放在评论上方」
  7. 最后得到一个 script 标签,等会填入下面的组件中,去掉data-、连字符变为小驼峰写法

然后安装 giscus 依赖:

pnpm add @giscus/react

2. 创建评论组件

src/components/GiscusComment.tsx 创建评论组件:

import Giscus from '@giscus/react';
import { useColorMode } from '@docusaurus/theme-common';

export default function GiscusComment() {
const { colorMode } = useColorMode();
const giscusTheme = colorMode === 'dark' ? 'dark' : 'light';
return (
<Giscus
id="comments"
repo="填入你的仓库名"
repoId="填入你的repoId"
category="填入你的category"
categoryId="填入你的categoryId"
mapping="pathname"
term="Welcome to @giscus/react component!"
strict="0"
reactionsEnabled="1"
emitMetadata="0"
inputPosition="top"
theme={giscusTheme}
lang="zh-CN"
loading="lazy"
/>
);
}

如果在使用 useColorMode 时报错,可以安装依赖:pnpm add @docusaurus/theme-common

3. 配置主题

执行以下命令,会出现 src/theme/BlogPostItem 目录:

pnpm run swizzle @docusaurus/theme-classic BlogPostItem --wrap --typescript

如果项目不是使用 TS,可以省略 --typescript参数。

修改 src/theme/BlogPostItem/index.tsx

import React from 'react';
import BlogPostItem from '@theme-original/BlogPostItem';
import type BlogPostItemType from '@theme/BlogPostItem';
import type { WrapperProps } from '@docusaurus/types';
import GiscusComment from '@site/src/components/GiscusComment';
import { useLocation } from '@docusaurus/router';

type Props = WrapperProps<typeof BlogPostItemType>;

export default function BlogPostItemWrapper(props: Props): JSX.Element {
const location = useLocation();
const isBlogPostPage =
location.pathname.startsWith('/blog/') &&
location.pathname !== '/blog' &&
!location.pathname.startsWith('/blog/tags') &&
!location.pathname.startsWith('/blog/page');

return (
<>
<BlogPostItem {...props} />
{isBlogPostPage && <GiscusComment />}
</>
);
}

通过判断页面路由,只在博客详情页显示评论。过滤以下路径,否则也会显示评论:

  • 博客列表首页: /blog
  • 博客列表分页: /blog/page/xxx
  • 某类标签的列表页: /blog/tags/xxx