添加最后修改时间
学习如何构建一个 remark 插件,该插件可将最后修改时间添加到 Markdown 和 MDX 文件的 frontmatter 中。使用此属性可以在你的页面中显示修改时间。
本方法基于仓库的 Git 历史记录计算时间,在某些部署平台上可能不准确。你的托管服务商可能正在执行浅克隆 (shallow clones),这不会检索完整的 git 历史记录。
-
安装辅助包
安装
Day.js
来修改和格式化时间终端窗口 npm install dayjs终端窗口 pnpm add dayjs终端窗口 yarn add dayjs -
创建一个 Remark 插件
这个插件使用
execSync
来运行一个 Git 命令,该命令以 ISO 8601 格式返回最新提交的时间戳。然后,该时间戳被添加到文件的 frontmatter 中。remark-modified-time.mjs import { execSync } from "child_process";export function remarkModifiedTime() {return function (tree, file) {const filepath = file.history[0];const result = execSync(`git log -1 --pretty="format:%cI" "${filepath}"`);file.data.astro.frontmatter.lastModified = result.toString();};}使用文件系统代替 Git
虽然使用 Git 是从文件中获取最后修改时间戳的推荐方法,但也可以使用文件系统的修改时间。这个插件使用
statSync
来获取文件的mtime
(修改时间),并以 ISO 8601 格式表示。然后,该时间戳被添加到文件的 frontmatter 中。remark-modified-time.mjs import { statSync } from "fs";export function remarkModifiedTime() {return function (tree, file) {const filepath = file.history[0];const result = statSync(filepath);file.data.astro.frontmatter.lastModified = result.mtime.toISOString();};} -
将插件添加到你的配置中
astro.config.mjs import { defineConfig } from 'astro/config';import { remarkModifiedTime } from './remark-modified-time.mjs';export default defineConfig({markdown: {remarkPlugins: [remarkModifiedTime],},});现在,所有的 Markdown 文档的 frontmatter 中都会有一个
lastModified
属性。 -
显示最后修改时间
如果你的内容存储在内容集合中,可以从
render(entry)
函数中访问remarkPluginFrontmatter
。然后在模板中你希望它出现的任何地方渲染lastModified
。src/pages/posts/[slug].astro ---import { getCollection, render } from 'astro:content';import dayjs from "dayjs";import utc from "dayjs/plugin/utc";dayjs.extend(utc);export async function getStaticPaths() {const blog = await getCollection('blog');return blog.map(entry => ({params: { slug: entry.id },props: { entry },}));}const { entry } = Astro.props;const { Content, remarkPluginFrontmatter } = await render(entry);const lastModified = dayjs(remarkPluginFrontmatter.lastModified).utc().format("HH:mm:ss DD MMMM YYYY UTC");---<html><head>...</head><body>...<p>Last Modified: {lastModified}</p>...</body></html>如果你正在使用 Markdown 布局,可以在你的布局模板中使用来自
Astro.props
的lastModified
frontmatter 属性。src/layouts/BlogLayout.astro ---import dayjs from "dayjs";import utc from "dayjs/plugin/utc";dayjs.extend(utc);const lastModified = dayjs().utc(Astro.props.frontmatter.lastModified).format("HH:mm:ss DD MMMM YYYY UTC");---<html><head>...</head><body><p>{lastModified}</p><slot /></body></html>