Astro Frontmatter 簡介
🧠 什麼是 frontmatter?
在 Astro 中,frontmatter 是寫在 Markdown 檔案最上方的一段 YAML 設定區塊,用來定義這篇文章的資料。
預設frontmatter:
---
title: 'First post'
description: 'Lorem ipsum dolor sit amet'
pubDate: 'Jul 08 2022'
heroImage: '../../assets/blog-placeholder-3.jpg'
---
你可以把它理解成:
👉「這篇文章的 metadata(資料)」 👉「文章的設定中心」
🚀 為什麼 frontmatter 很重要?
因為它可以讓你的文章:
- 有標題、描述(SEO)
- 可以分類、加標籤
- 可以控制是否發布
- 可以決定 UI 顯示(封面圖、精選文章)
👉 本質上,它就是你「部落格系統的資料庫」
🧩 基本用法
Markdown 內定義
---
title: My First Post
date: 2026-03-28
tags: [Astro, Blog]
---
在 layout 中使用
---
const { frontmatter } = Astro.props;
---
<h1>{frontmatter.title}</h1>
<p>{frontmatter.date}</p>
👉 Astro 會自動幫你解析 frontmatter,並傳進 layout。
🔓 可以自訂欄位嗎?
👉 可以,而且完全沒有限制!
---
title: My Post
category: Tech
tags: [Astro, Frontend]
readingTime: 5
featured: true
---
你可以自由新增:
categorytagscoverreadingTime任何你需要的欄位
👉 Astro 不會限制你。
⚠️ 但這也是一個陷阱
因為 Astro 不會幫你檢查:
- 拼錯欄位(
titel❌) - 型別錯誤(
tags: "astro"❌)
👉 這就是為什麼官方推薦使用「Content Collections」
🔥 官方推薦:Content Collections(強烈建議)
import { defineCollection, z } from 'astro:content';
const blog = defineCollection({
schema: z.object({
title: z.string(),
date: z.date(),
tags: z.array(z.string()),
}),
});
export const collections = { blog };
好處
- ✔ 自動型別檢查
- ✔ build 時驗證錯誤
- ✔ IDE 自動補全
👉 等於幫 frontmatter 加上「結構與規範」
🧱 實戰建議結構(Blog 專用)
這是一套可直接用在 production 的設計:
---
# 基本資訊
title: Astro in brief
description: Find out what makes Astro awesome!
author: Himanshu
# 發佈控制
date: 2026-03-28
updated: 2026-03-28
published: true
draft: false
# 分類
category: Tech
tags: [Astro, Markdown]
# SEO
slug: astro-in-brief
canonical: https://yourdomain.com/blog/astro-in-brief
ogImage: /images/cover.jpg
# UI
cover: /images/cover.jpg
coverAlt: Astro Cover
readingTime: 5
featured: false
# 功能開關
toc: true
comments: true
---
🧠 設計思路解析
📅 發佈控制
published/draft→ 控制是否顯示date→ 排序用updated→ SEO 加分
🏷 分類 vs 標籤
category→ 單一分類(UI 好處理)tags→ 多標籤(搜尋 / SEO)
🔍 SEO 欄位
slug→ 自訂網址canonical→ 避免重複內容ogImage→ 社群分享圖
🎨 UI 欄位
cover→ 封面圖readingTime→ 使用者體驗featured→ 首頁精選
🧩 frontmatter 支援的資料型別
因為是 YAML,你可以使用:
title: Hello
views: 100
published: true
tags:
- Astro
- Blog
seo:
title: Custom SEO Title
description: SEO Description
👉 支援巢狀物件(非常強大)
⚠️ 常見錯誤
❌ 忘記用 ---
title: Hello
👉 必須包在 --- 之間
❌ YAML 格式錯誤
tags: [Astro Blog] ❌
👉 正確:
tags: [Astro, Blog]
❌ 型別錯誤
tags: Astro ❌
👉 應該是:
tags: [Astro]
🧠 總結
frontmatter 在 Astro 中:
- ✔ 是 Markdown 的資料來源
- ✔ 完全自由(可以自訂欄位)
- ✔ 是部落格系統的核心
但同時:
- ⚠ 沒有驗證機制
- 🔥 建議搭配 Content Collections 使用
🚀 延伸建議
如果你要打造完整部落格:
- 分類頁(category page)
- 標籤頁(tag page)
- SEO meta 自動生成
- 精選文章系統
👉 frontmatter 就是整個系統的基礎,以上內容由 ChatGPT 產生
📖 後記
目前我使用Astro來重建我的Blog,之前已經有過用其他的靜態網站生成工具
我也偏好使用Markdown來編輯文件,md檔的標頭檔的寫法,各家略有不同
所以就請 ChatGPT 來幫我解答,這篇只是第一篇
我的目標是自訂frontmatter的欄位,來自行定義如文章排序或狀態 :)