마지막 수정 시간 추가
Markdown 및 MDX 파일의 사용자 지정 프런트매터 속성으로 마지막 수정 시간을 추가하는 mdast 플러그인을 만드는 방법을 알아보세요. 이 속성을 사용해 페이지에 수정 시간을 표시할 수 있습니다.
이 레시피는 리포지토리의 Git 기록을 기반으로 시간을 계산하므로 일부 배포 플랫폼에서는 정확하지 않을 수 있습니다. 호스트가 전체 Git 기록을 가져오지 않는 얕은 복제를 수행할 수 있습니다.
레시피
섹션 제목: “레시피”-
사용하는 Markdown 프로세서에 따라 다음 패키지를 설치합니다.
- 시간을 조작하고 형식을 지정하기 위한
Day.js satteri()프로세서를 구성하기 위한@astrojs/markdown-satteri- Sätteri
mdast플러그인을 만들기 위한satteri
터미널 창 npm install dayjs @astrojs/markdown-satteri satteri터미널 창 pnpm add dayjs @astrojs/markdown-satteri satteri터미널 창 yarn add dayjs @astrojs/markdown-satteri satteri- 시간을 조작하고 형식을 지정하기 위한
Day.js unified()프로세서를 사용하기 위한@astrojs/markdown-remark
터미널 창 npm install dayjs @astrojs/markdown-remark터미널 창 pnpm add dayjs @astrojs/markdown-remark터미널 창 yarn add dayjs @astrojs/markdown-remark - 시간을 조작하고 형식을 지정하기 위한
-
mdast 플러그인을 만듭니다.
이 플러그인은
execSync를 사용해 가장 최근 커밋의 타임스탬프를 ISO 8601 형식으로 반환하는 Git 명령을 실행합니다. 그런 다음 타임스탬프를 파일의 프런트매터에 추가합니다.src/mdast/mdast-modified-time.ts import { execSync } from "node:child_process";import { fileURLToPath } from "node:url";import { defineMdastPlugin } from "satteri";export const mdastModifiedTimePlugin = defineMdastPlugin({name: "mdast-modified-time",before(root, context) {if (!context.fileURL) return;const filepath = fileURLToPath(context.fileURL);const result = execSync(`git log -1 --pretty="format:%cI" "${filepath}"`);if (context.data.astro !== undefined) {context.data.astro.frontmatter.lastModified = result.toString();}},});remark-modified-time.mjs import { execSync } from "node: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 형식으로 가져옵니다. 그런 다음 타임스탬프를 파일의 프런트매터에 추가합니다.src/mdast/mdast-modified-time.ts import { statSync } from "node:fs";import { fileURLToPath } from "node:url";import { defineMdastPlugin } from "satteri";export const mdastModifiedTimePlugin = defineMdastPlugin({name: "mdast-modified-time",before(node, context) {if (!context.fileURL) return;const filepath = fileURLToPath(context.fileURL);const result = statSync(filepath);if (context.data.astro !== undefined) {context.data.astro.frontmatter.lastModified = result.mtime.toISOString();}},});remark-modified-time.mjs import { statSync } from "node: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 { satteri } from "@astrojs/markdown-satteri";import { defineConfig } from "astro/config";import { mdastModifiedTimePlugin } from "./src/mdast/mdast-modified-time";export default defineConfig({markdown: {processor: satteri({mdastPlugins: [mdastModifiedTimePlugin],}),},});astro.config.mjs import { unified } from "@astrojs/markdown-remark";import { defineConfig } from "astro/config";import { remarkModifiedTime } from "./remark-modified-time.mjs";export default defineConfig({markdown: {processor: unified({remarkPlugins: [remarkModifiedTime],}),},});이제 모든 Markdown 문서의 프런트매터에
lastModified속성이 포함됩니다. -
마지막 수정 시간을 표시합니다.
콘텐츠가 콘텐츠 컬렉션에 저장된 경우
render()함수에서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><meta charset="utf-8" /><title>{entry.data.title}</title></head><body><title>{entry.data.title}</title><p>마지막 수정: {lastModified}</p><Content /></body></html>Markdown 레이아웃을 사용하는 경우 레이아웃 템플릿의
Astro.props에서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><meta charset="utf-8" /></head><body><p>{lastModified}</p><slot /></body></html>