blog/plugin/remark-reading-time.ts

17 lines
547 B
TypeScript
Raw Normal View History

2023-08-31 08:07:03 +00:00
import getReadingTime from "reading-time";
2024-12-17 22:50:57 +00:00
import { toString as mdastToString } from "mdast-util-to-string";
2023-09-01 15:09:01 +00:00
import type { RemarkPlugin } from "@astrojs/markdown-remark";
2023-08-31 08:07:03 +00:00
2023-09-01 15:09:01 +00:00
const remarkReadingTime: RemarkPlugin = () => {
2024-04-05 15:34:32 +00:00
return (tree, { data }) => {
2024-12-17 22:50:57 +00:00
const textOnPage = mdastToString(tree);
2023-08-31 08:07:03 +00:00
const readingTime = getReadingTime(textOnPage);
2023-09-01 15:09:01 +00:00
2023-08-31 08:07:03 +00:00
// readingTime.text will give us minutes read as a friendly string,
// i.e. "3 min read"
data.astro.frontmatter.minutesRead = readingTime.text;
};
2023-09-01 15:09:01 +00:00
};
export default remarkReadingTime;