博客评论由 GitHub 提供支持

2025-06-09

博客评论由 GitHub 提供支持

在博客开发的最后阶段,我开始研究处理评论的最佳方式。在浏览了一些常用工具(例如Disqus)之后,我偶然发现了一系列关于使用 GitHub 进行评论的博客文章(1、2、3等等) 。随着我不断挖掘,我注意到上述博客文章中有一个共同的模式——人们纷纷放弃 Disqus ,转而使用 GitHub 解决方案原因是 Disqus 速度慢、功能臃肿,而且侵犯隐私。现在我确信,利用 GitHub 才是最佳选择。

于是我开始记录所有必要的组件。比如处理 GitHub API 速率限制、设计评论部分的样式、自动为每个博文创建 GitHub 问题等等。然后我偶然发现了Utterances

话语

Utterances 将所有你需要在博客上创建 GitHub 支持的评论区所需的繁琐工作打包成一个GitHub 应用。它是开源的,甚至自带深色主题!我已经将它集成到我的博客中,可以确认整个过程非常轻松。以下是我设置它的步骤列表。

创建公共 GitHub 存储库

第一步是创建一个公共 GitHub 存储库来存储我博客的评论

存储库

安装 Utterances App

然后我必须将Utterances GitHub 应用程序安装到我上面创建的存储库中。

话语装置

生成脚本标签

然后,我使用Utterances 网站上的配置部分生成了稍后会在博客上加载的脚本标签。我的脚本标签如下:

<script src="https://utteranc.es/client.js"
        repo="loizoskounios/blog-comments-tracker"
        issue-term="title"
        theme="github-light"
        crossorigin="anonymous"
        async>
</script>
Enter fullscreen mode Exit fullscreen mode

加载脚本

剩下的就是把脚本加载到我的 Gatsby 博客里了。还好,在 React 中设置起来相当简单。

要在 React 中加载脚本,我必须手动创建 script 元素,并将其作为子元素附加到其他元素。我使用document全局变量创建了 script 元素,并使用 Reactref保存了指向放置该 script 元素的组件的引用。这就是我最终的做法,去除了所有不必要的干扰(例如 Gatsby 静态查询、样式组件等等)。

import React from 'react';

class Comments extends React.Component {
  constructor(props) {
    super(props);

    this.commentsEl = React.createRef();
    this.state = { status: 'pending' };
  }

  componentDidMount() {
    const scriptEl = document.createElement('script');
    scriptEl.onload = () => this.setState({ status: 'success' });
    scriptEl.onerror = () => this.setState({ status: 'failed' });
    scriptEl.async = true;
    scriptEl.src = 'https://utteranc.es/client.js';
    scriptEl.setAttribute('repo', 'loizoskounios/blog-comments-tracker');
    scriptEl.setAttribute('issue-term', 'title');
    scriptEl.setAttribute('theme', 'github-light');
    scriptEl.setAttribute('crossorigin', 'anonymous');
    this.commentsEl.current.appendChild(scriptEl);
  }

  render() {
    const { status } = this.state;

    return (
      <div className="comments-wrapper">
        {status === 'failed' && <div>Error. Please try again.</div>}
        {status === 'pending' && <div>Loading script...</div>}
        <div ref={this.commentsEl} />
      </div>
    );
  }
}

export default Comments;
Enter fullscreen mode Exit fullscreen mode

最终结果

这是虚拟博客文章的最终结果。

带有“话语”评论区的帖子

如果你想了解这个功能的具体工作原理,Utterances 已经集成在我的博客中了。你可以把它当作一个游乐场来使用。

鏂囩珷鏉ユ簮锛�https://dev.to/loizoskounios/blog-comments-powered-by-github-3dp2
PREV
社交媒体信息流背后的隐藏算法
NEXT
理解 TypeScript 生成器