添加阅读时间
创建一个在你的 Markdown 或 MDX 文件的 frontmatter 中添加阅读所需时间的 remark 插件。使用该属性来为每个页面显示所需的阅读时间。
操作步骤
段落标题 操作步骤-
安装辅助包
安装如下两个辅助包:
reading-time
用于计算阅读分钟数mdast-util-to-string
用于从你的 Markdown 中提取所有文本
终端窗口 npm install reading-time mdast-util-to-string终端窗口 pnpm install reading-time mdast-util-to-string终端窗口 yarn add reading-time mdast-util-to-string -
创建一个 remark 插件
该插件使用 mdast-util-to-string
包来获取 Markdown 文件的文本内容,然后将文本传递给 reading-time
包以计算阅读所需的分钟数。
import getReadingTime from 'reading-time';import { toString } from 'mdast-util-to-string';
export function remarkReadingTime() { return function (tree, { data }) { const textOnPage = toString(tree); const readingTime = getReadingTime(textOnPage); // readingTime.text 会以友好的字符串形式给出阅读时间,例如 "3 min read"。 data.astro.frontmatter.minutesRead = readingTime.text; };}
-
将插件添加到你的配置中:
astro.config.mjs import { defineConfig } from 'astro/config';import { remarkReadingTime } from './remark-reading-time.mjs';export default defineConfig({markdown: {remarkPlugins: [remarkReadingTime],},});现在所有的 Markdown 文档的 frontmatter 中都会有一个计算出来的
minutesRead
属性。 -
显示阅读时间
如果你的博客文章存储在内容集合中,通过
entry.render()
函数获取remarkPluginFrontmatter
,然后在模板中你喜欢的位置渲染minutesRead
。src/pages/posts/[slug].astro ---import { CollectionEntry, getCollection } from 'astro:content';export async function getStaticPaths() {const blog = await getCollection('blog');return blog.map(entry => ({params: { slug: entry.slug },props: { entry },}));}const { entry } = Astro.props;const { Content, remarkPluginFrontmatter } = await entry.render();---<html><head>...</head><body>...<p>{remarkPluginFrontmatter.minutesRead}</p>...</body></html>如果你使用的是 Markdown 布局,在布局模板中通过
Astro.props
来获取 frontmatter 中的minutesRead
属性。src/layouts/BlogLayout.astro ---const { minutesRead } = Astro.props.frontmatter;---<html><head>...</head><body><p>{minutesRead}</p><slot /></body></html>
更多操作指南
-
状态共享
学习如何使用 Nano Stores 在框架组件之间共享状态
-
添加 RSS 摘要
通过向你的 Astro 网站添加 RSS 摘要让用户来订阅你的内容。
-
安装一个 Vite 或 Rollup 插件
了解如何通过向项目添加 Rollup 插件来导入 YAML 数据。
-
构建自定义图像组件
了解如何使用 getImage 函数构建支持媒体查询的自定义图像组件
-
使用 API 路由构建表单
了解如何使用 JavaScript 发送表单到 API 路由
-
在 Astro 页面中构建 HTML 表单
了解如何在 Astro 页面中构建 HTML 表单并在你的 frontmatter 中处理提交请求
-
在 Astro 中使用 Bun
了解如何在 Astro 站点中使用 Bun。
-
调用服务器端点
了解如何在 Astro 中调用服务器端点
-
校验验证码
了解如何创建一个 API 路由并从客户端进行获取。
-
用 Docker 来构建你的 Astro 网站
了解如何使用 Docker 来构建你的 Astro 网站。
-
Dynamically Import Images
Learn how to dynamically import images using Vite's import.meta.glob function
-
为链接添加图标
了解如何安装 rehype 插件并为你 Markdown 文件中的链接添加图标
-
添加 i18n 功能
通过动态路由和内容集合来让你的 Astro 站点支持国际化。
-
添加最后修改时间
编写一个在你的 Markdown 和 MDX 文件里添加最后修改时间的 remark 插件。
-
添加阅读时间
编写一个在你的 Markdown 和 MDX 文件里添加阅读所需时间的 remark 插件。
-
在 Astro 组件中共享状态
了解如何通过 Nano Stores 在 Astro 组件中共享状态
-
使用流式处理来提升页面性能
了解如何使用流式处理来提升页面性能
-
使用 Tailwind Typography 美化渲染后的 Markdown
了解如何使用 @tailwind/typography 美化你渲染后的 Markdown