Skip to main content

搭建博客站点

· 2 min read

本文主要记录个人站点 whinc.github.io 的搭建过程,以及后续的维护更新,可以看做是个人站点自身的一份 changelog

站点基于 Docusaurus 搭建,其提供了博客、文档(MDX)、React 单单页应用多种模式构建站点,可以满足大部分的个人定制化的需求。

添加文章评论 - Giscus

giscus 是一个基于 Github 的开源免费的评论系统,其原理是基于 github 的 discussion 功能来实现评论的存储。

接入步骤:参考 How to add Giscus comments to Docusaurus,参考文档giscus 配置页giscus-component

添加 MDX 互动代码 - RunKit

RunKit 提供运行在网页中嵌入 Node.js 代码片段,并执行显示输出的能力,适合交互式演示代码片段。

接入步骤:

  1. 封装 RunKitEmbed 组件:RunKit Embed 文档提供了原生 JS 嵌入 RunKit 的方法,也提供了 WebComponent 和 React 的封装,不过 React 的封装版本太旧了(react 16),于是自行封装了一个 React hooks 组件(如下),可在 MDX 中直接使用。
import CodeBlock from "@theme/CodeBlock";
import { useExternal } from "ahooks";
import { Spin } from "antd";
import React, { useEffect, useRef, useState } from "react";

// 参考: https://runkit.com/docs/embed
type RunKitEmbedProps = EmbedOptions;

export default function RunKitEmbed({ source, ...props }: RunKitEmbedProps) {
const [rendering, setRendering] = useState(false);
const status = useExternal("https://embed.runkit.com", {
type: "js",
js: {
defer: true,
},
});
const ref = useRef<HTMLDivElement>(null);

useEffect(() => {
if (status === "ready" && window.RunKit && ref.current) {
setRendering(true);
const res = window.RunKit.createNotebook({
element: ref.current,
nodeVersion: "18.x.x",
source: source.trim(),
...props,
});
res.onLoad = () => setRendering(false);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [status]);

return (
<>
{(status !== "ready" || rendering) && (
<CodeBlock language="javascript">{source.trim()}</CodeBlock>
)}
<div ref={ref}></div>
{process.env.NODE_ENV === "development" && (
<Spin spinning={status === "loading"} tip="加载 RunKit ...">
<Spin spinning={status === "ready" && rendering}></Spin>
</Spin>
)}
</>
);
}
  1. 在 MDX 中嵌入 RunKit:引入上面封装的 RunKitEmbed 组件,传入 source 源码即可,如果想对 RunKit 做细粒度的控制,参考上面的 RunKit Embed 文档
import RunKitEmbed from '@site/src/components/RunKitEmbed';

<RunKitEmbed source={`
const knex = require('knex');
const db = knex({client: 'mysql'});
await db.table('aa').select('b', 'c').toSQL().toNative()
`} />

添加 MD/MDX 图表 - Mermaid

mermaid 是基于 javascript 的纯文本图渲染库,常用于扩展 Markdown 的图表达能力,支持 Sequence/Flow/Class/State/Git/Mindmap等多种图。

接入方式:参考 docusaurus diagrams