Axi's Blog
在 Astro 中使用 WalineBlur image

前言#

在搭建博客的时候,往往一个评论系统会是一个刚需,这样可以和读者进行互动,而 Waline 是一个不错的评论系统。

在此之前笔者尝试过使用 Giscus 作为评论系统,但是一方面这要求你的仓库需要开源,而我的博客主题还没有完全重构好;另一方面,Giscus 的评论需要通过 GitHub 的 API 获取(本身是基于 Discussion 建立的),这意味着要接受 Github 在大陆被 DNS 污染导致的降速(虽然可以 lazy load)以及必须要注册 Github 账号并且登录,这毫无疑问将评论的受众限制到了编程人员为主的群体,而不是更加广泛。假如读者希望使用 Giscus 搭建评论,见 这个教程

Waline 可以基于 Leancloud 以及 Vercel 搭建,并且以组件的形式嵌入到 Astro 中,虽然需要后端,但是项目本身做了很好的封装,用户不需要了解任何内容,只需要跟着流程走下来就好。其安装教程为 官方文档,全部手把手进行即可。

值得注意的是,第一个在 https://your-waline-server-url/ui/ 中注册的账号是管理员,务必在部署后直接先行登录。

在 Astro 中集成 Waline#

为了在 Astro 博客中集成 Waline,我们通常会创建一个 Astro 组件来封装 Waline 的所有逻辑和样式。这样可以保持代码的整洁和可维护性。

核心原理#

集成 Waline 的基本原理是:

  • 引入 Waline 客户端库: 在前端页面中加载 Waline 的 JavaScript 和 CSS 文件。
  • 提供挂载点: 在 HTML 中创建一个特定的 div 元素作为 Waline 评论界面的容器。
  • 初始化 Waline: 通过调用 Waline 客户端库提供的 init 方法,将评论系统挂载到指定容器,并传入必要的配置参数(如后端服务地址、表情包等)。

说白了直接先运行 npm install @waline/client 安装客户端库,然后直接在组件中引入即可。

实现#

以下是我的一个实现,可供参考。同时在当下,假如说你嵌入 Waline,实际上 Cursor 之类的 AI 工具也可以帮你生成。

---
import '@waline/client/style'
const { class: className } = Astro.props
---

<comment-component>
  <div id='waline' class={`not-prose ${className}`}>
    Comment seems to stuck. Try to refresh?✨
  </div>
</comment-component>

<script>
  import { init as walineInit } from '@waline/client'
  const walineConfig = {
    server: 'https://your-waline-server-url/',
    emoji: [
      'weibo',
      'alus',
      'bilibili',
      'qq'
    ],
    additionalConfigs: {
      locale: {
        placeholder: '欢迎留言~(支持Markdown语法)'
      }
    }
  }

  class Comment extends HTMLElement {
    constructor() {
      super()
    }

    connectedCallback() {
      const walineInstance = walineInit({
        el: '#waline',
        serverURL: walineConfig.server,
        reaction: [],
        dark: 'html.dark',
        pageview: true,
        comment: true,
        ...walineConfig.additionalConfigs
      })
      walineInstance?.update()
    }
  }

  customElements.define('comment-component', Comment)
</script>

<style>
  :global(.dark) #waline {
    --waline-bg-color: var(--card-bg);
    --waline-bg-color-light: var(--btn-plain-bg-hover);
  }

  :global(.wl-count) {
    color: var(--waline-dark-grey);
  }

  :global(.wl-editor) {
    padding: 0.35em 0.5em;
    width: calc(100% - 2em);
  }

  :global(.wl-edit) {
    color: var(--waline-dark-grey);
  }

  :global(#wl-edit)::placeholder {
    color: var(--waline-dark-grey);
  }

  :global(.wl-panel) {
    margin: .5em 0;
    border: none;
  }
</style>
astro

后记#

大概就是这样,因为想写点 Blog,所以写了这个,希望对你有帮助,假如需要协助,欢迎评论区评论。

在 Astro 中使用 Waline
https://axi404.top/blog/waline-install
Author 阿汐
Published at July 16, 2025
Comment seems to stuck. Try to refresh?✨