添加最后修改时间
学习如何编写一个在你的 Markdown 或 MDX 文件的 frontmatter 中添加最后修改时间的 remark 插件。使用这个属性在你的页面中显示最后修改时间。
操作步骤
段落标题 操作步骤-
安装辅助包
安装用于修改和格式化时间的
Day.js
:Terminal window npm install dayjsTerminal window pnpm install dayjsTerminal window 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
获取文件的 ISO 8601 格式的mtime
(修改时间),然后将时间戳添加到文件的 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
属性。 -
显示最后修改时间
如果你的博客文章存储在内容集合中,通过
entry.render()
函数获取remarkPluginFrontmatter
,然后在模板中你喜欢的位置渲染lastModified
。src/pages/posts/[slug].astro ---import { CollectionEntry, getCollection } 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.slug },props: { entry },}));}const { entry } = Astro.props;const { Content, remarkPluginFrontmatter } = await entry.render();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
来获取 frontmatter 中的lastModified
属性。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>