添加最后修改时间
学习如何编写一个在你的 Markdown 或 MDX 文件的 frontmatter 中添加最后修改时间的 remark 插件。使用这个属性在你的页面中显示最后修改时间。
:::note[使用 Git 历史记录]此方案根据存储库的 Git 历史记录来计算时间,在某些部署平台上可能不准确。你的主机可能正在执行 浅克隆,而浅克隆并不会检索完整的 Git 历史记录。:::
操作步骤
安装辅助包
安装用于修改和格式化时间的
Day.js:npm install dayjspnpm add dayjsyarn add dayjs创建一个 remark 插件
这个插件使用
execSync运行一个 Git 命令获取最后一次提交的 ISO 8601 时间戳,然后将时间戳添加到文件的 frontmatter 中。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获取文件的 ISO 8601 格式的mtime(修改时间),然后将时间戳添加到文件的 frontmatter 中。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(); }; }将插件添加到你的配置中
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。--- 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>最新修改时间:{lastModified}</p> ... </body> </html>如果你使用的是 Markdown 布局,在布局模板中通过
Astro.props来获取 frontmatter 中的lastModified属性。--- 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>