博客功能
代码高亮
相关文章
Fuse.js - https://www.fusejs.io
npm install fuse.js
import Fuse from 'fuse.js'
const articles = [
{
"title": "Old Man's War",
"author": {
"firstName": "John",
"lastName": "Scalzi"
}
},
{
"title": "The Lock Artist",
"author": {
"firstName": "Steve",
"lastName": "Hamilton"
}
}
/*...*/
]
const options = { keys: ['title', 'author.firstName'] }
// Create the Fuse index
const myIndex = Fuse.createIndex(options.keys, articles)
// initialize Fuse with the index
const fuse = new Fuse(articles, options, myIndex)
阅读时间
通过 reading-time
库可以为我们的文章添加阅读时间、文章字数元数据。
npm i reading-time
通过导出的 readingTime
方法计算文章的阅读时间,然后将数据写到 meta
变量中。
import readingTime from 'reading-time';
export function getPostBySlug(slug: string) {
...
const { data, content, excerpt } = matter(fileContents, {
excerpt: true,
});
const readTime = readingTime(content);
const meta = { ...data, readingTime: readTime };
...
}
评论功能
静态网站的评论实现有一种方案是借助 Github Issue 或者 Github Discussions 封装的插件形式集成进来。数据存储在第三方,同时也解决了登录授权问题。
下面是根据次方案实现的三个库:
- giscus - 可借助组件库在 React、Vue 和 Svelte 中使用,支持多种语言
- gitalk - 基于 Github Issue 和 Preact 开发的评论插件
- utterances - 借助 Github issues 实现的轻量的评论组件,giscus 灵感就是来源于它
这里采用 Giscus 评论功能为例,进行讲解。先安装 @giscus/react
库
npm install @giscus/react --save
然后在项目中封装一个全局的评论组件:
import Giscus from '@giscus/react';
import { useTheme } from 'next-themes';
const GiscusComment = ({ isEnableReaction = false }) => {
const { theme } = useTheme();
return (
<div className='mt-5 mb-2'>
<Giscus
repo='fantingsheng/repo.id'
repoId='R_kgDOJoIh**'
category='General'
categoryId='DIC_kwDOJoIhfc4CW6cJ'
mapping='pathname'
reactionsEnabled={isEnableReaction ? '1' : '0'}
emitMetadata='1'
inputPosition='top'
theme={theme === 'dark' ? 'transparent_dark' : 'light'}
lang='en'
loading='lazy'
/>
</div>
);
};
export default GiscusComment;
文章 RSS 订阅
RSS 是网站内容常见的订阅方式,而 feed
库正是该功能的封装。