Astro 博客添加 Twikoo 评论
实现思路:在 Astro 项目中创建一个用于显示评论的组件,然后在这个组件中引入 Twikoo 的代码片段,示例代码如下:
<div id="tcomment"></div>
<script src="https://cdn.staticfile.org/twikoo/1.6.16/twikoo.all.min.js"></script>
<script>
twikoo.init({
envId: "您的环境 id", // 腾讯云环境填 envId;Vercel 环境填地址(https://xxx.vercel.app)
el: "#tcomment", // 容器元素
// region: 'ap-guangzhou', // 环境地域,默认为 ap-shanghai,腾讯云环境填 ap-shanghai 或 ap-guangzhou;Vercel 环境不填
// path: location.pathname, // 用于区分不同文章的自定义 js 路径,如果您的文章路径不是 location.pathname,需传此参数
// lang: 'zh-CN', // 用于手动设定评论区语言,支持的语言列表 https://github.com/imaegoo/twikoo/blob/main/src/client/utils/i18n/index.js
});
</script>
具体操作步骤如下:
前往 Twikoo 网站按文档步骤部署好云函数,在你的 Astro 项目 src/components
路径下新建一个评论组件,如 Comments.astro
,将 Twikoo 的评论代码复制进去,这里以 Vercel 部署为例
<div id="tcomment"></div>
<script
src="https://cdn.staticfile.org/twikoo/1.6.16/twikoo.all.min.js"
data-astro-ignore></script>
<script>
twikoo.init({
envId: "https://yourname.vercel.app/", // 替换为你的 Vercel 地址
el: "#tcomment", // 指定评论容器元素
});
</script>
上面的代码中,data-astro-ignore
属性是告诉 Astro 不要对这个脚本进行优化,这样脚本将在页面加载时立即执行,在组件中引入 Twikoo 代码后,便可以将它添加到你的文章页面中了。将以下代码复制到 layouts/BlogPost.astro
页面中的 import
内容里。
import Comments from '../components/Comments.astro';
完整代码如下:
---
import type { CollectionEntry } from "astro:content";
import BaseHead from "../components/BaseHead.astro";
import Header from "../components/Header.astro";
import Footer from "../components/Footer.astro";
import FormattedDate from "../components/FormattedDate.astro";
import Comments from "../components/Comments.astro";
type Props = CollectionEntry<"blog">["data"];
const { title, description, pubDate, updatedDate, heroImage } = Astro.props;
---
接着在 BlogPost.astro
页面中选择一个合适的位置插入评论组件 <Comments />
,保存并部署项目后即可在你的文章也看到评论功能了。