I am using CloudFlare’s CDN service - https://cdnjs.com/libraries/twikoo. The integrity
will change every version.
Create Comment.astro
under src/components
with below:
<div id="tcomment"></div>
<script>
// or `<script data-cfasync="false">` if you are on Cloudflare
document.addEventListener("astro:page-load", () => {
function loadTwikoo() {
const commentsContainer = document.getElementById("tcomment");
if (commentsContainer) {
const script = document.createElement("script");
script.src =
"https://cdnjs.cloudflare.com/ajax/libs/twikoo/1.6.32/twikoo.all.min.js";
script.defer = true;
script.integrity =
"sha512-oLwAGOCSlT4rWN1IV2lpvUWOwYPo1xhJyrIhFk6jVa+S7Vi2AKvr0rEuvHZAkVd9p3sJBTMcx2XabwK0HGxFuA==";
script.crossOrigin = "anonymous";
script.referrerPolicy = "no-referrer";
script.onload = () => {
const initScript = document.createElement("script");
initScript.innerHTML = `
twikoo.init({
envId: "https://comments.haobin.liang.london",
el: "#tcomment",
lang: "en-GB",
});
`;
document.body.appendChild(initScript);
};
document.body.appendChild(script);
}
}
loadTwikoo();
});
</script>
Place below in the page that you want to show the comment section.
---
import Comment from "~/components/Comment.astro";
---
<!-- The comment section -->
<Comment />
Source: Astro 添加 Twikoo 评论 by 老麦
Outdated - not automatically loaded since Astro v3
Twikoo is a comment system that can be easily deployed to cloud platforms with minimal work. I particularly like that it just blends into pages with zero styling!
Also, it has all features I am want for a comment system - e.g. emoji, admin, spam filtering, image upload, markdown, Katex, syntax highlighting and more - so no complaint at all.
Pre-requisite
Follow the quick start guide to deploy Twikoo backend.
Installing Twikoo package into the project
Install Twikoo with your package management. I am using pnpm
.
pnpm install twikoo
Adding frontend JS to Astro
Add below code to the bottom of pages you want to show.
<script>
import twikoo from "twikoo";
twikoo({
envId: "https://YOUR_TWIKOO_URL", // your environment ID or url
el: "#tcomment", // the container ID which will show the comment
lang: "en-GB", // language for the comment template. for the full list, refer to https://github.com/imaegoo/twikoo/blob/main/src/client/utils/i18n/index.js
}).then(() => {
console.log("comment loading success");
});
</script>
For example, I want to show comments on each post and about page. The layout is defined in /src/layouts/PostDetails.astro
and /src/layouts/AboutLayout.astro
.
Declaring Twikoo module
The Twikoo package doesn’t have any type declared; so it will show as error in development.
Declare the module in main .d.ts
file (in my case env.d.ts
) to remove errors.
// Remove twikoo import error
declare module "twikoo";
Adding the comment container placeholder
Place below code. The code should be on the same page.
<div id="tcomment"></div>
<!-- the attribute of this element to correlates to `el` in the JS -->
Viola. Job done! 👏👏👏