go to index

Astro使用Remark42搭建评论功能

read time 2 min read

配置Remark42得到url(打开url/web能够看到demo就可以了)

fly.io云部署 参考阿拉喵

二进制本地部署 参考luxiyue

Oauth配置 参考Matteo

Astro引入Remark42

源码来自Remark42官网

  1. 在components新建Remark42.tsx,代码如下
plaintext
import {useEffect} from 'preact/hooks'
interface Remark {
  changeTheme: (theme: string) => void;
}

interface RemarkConfig {
  host: string;
  site_id: string;
  url: string;
  theme: string;
  components: string[];
}

declare global {
  interface Window {
    REMARK42: Remark;
    remark_config: RemarkConfig;
  }
}

const insertScript = (id: string, parentElement: HTMLElement) => {
  const script = window.document.createElement('script')
  script.type = 'text/javascript'
  script.async = true
  script.id = id

  let url = window.location.origin + window.location.pathname
  if (url.endsWith('/')) {
    url = url.slice(0, -1)
  }

  const host = 'https://$(yourremarkurl)' // your url

  script.innerHTML = `
    var remark_config = {
      host: "${host}",
      site_id: "remark",
      url: "${url}",
      theme: "light",
      components: ["embed","last-comments"],
      locale: "zh"
    };
    !function(e,n){for(var o=0;o<e.length;o++){var r=n.createElement("script"),c=".js",d=n.head||n.body;"noModule"in r?(r.type="module",c=".mjs"):r.async=!0,r.defer=!0,r.src=remark_config.host+"/web/"+e[o]+c,d.appendChild(r)}}(remark_config.components||["embed"],document);`

  parentElement.appendChild(script)
}

const removeScript = (id: string, parentElement: HTMLElement) => {
  const script = window.document.getElementById(id)
  if (script) {
    parentElement.removeChild(script)
  }
}

const manageScript = () => {
  if (!window) {
    return () => {}
  }
  const {document} = window
  if (document.getElementById('remark42')) {
    insertScript('comments-script', document.body)
  }
  return () => removeScript('comments-script', document.body)
}

export function Remark42() {
  useEffect(manageScript, [])

  return (
    <>
      <div style={{ height: '20px' }}/>
      <h2>留言</h2>
      <div id="remark42"/>
    </>
  )
}
  1. 安装preact
plaintext
npm install @astrojs/preact

bun add @astrojs/preact astro preact
  1. astro.config.mjs添加新的渲染
plaintext
import preact from '@astrojs/preact';
...
export default defineConfig({
	site: Site,
	build: {
		format: 'file',
	},
	integrations: [
		preact(),
        ...
    ]
    ...

  1. 在layout中找到你想加入评论的地方 <Remark42 client:visible/>

然后就拥有和客人友好交流的功能了~