本文是快速实践流程,不是教程,需要基本的 Astro 知识才能看懂。
安装 astro,配套 shadcn
pnpm dlx shadcn@latest init --template astro写这篇文章时用的版本是 astro 7.4.8 。
配置内容集合
import { defineCollection } from "astro:content"import { glob } from "astro/loaders"import { z } from "astro/zod"
const blog = defineCollection({ loader: glob({ pattern: "**/*.md", base: "./src/data/blog" }), schema: z.object({ title: z.string(), publish_date: z.coerce.date(), updated_date: z.coerce.date().optional(), tags: z.array(z.enum(["开发", "Astro", "其他标签"])), }),})
export const collections = { blog }创建Markdown文章
路径是自定义的,但要与 src/content.config.ts 文件里 loader 对应的路径对齐。这里对应路径为 src/data/blog,在此路径下可创建多个文章,如:
---title: 示例文章publish_date: 2026-12-01tags: [开发, Astro]---
Markdown 内容在这里编辑。生成文章页面
创建生成文章页面代码文件,路径可根据需求自定义。
---import Layout from "@/layouts/main.astro"import { getCollection, render } from "astro:content"
export async function getStaticPaths() { const posts = await getCollection("blog") return posts.map((post) => ({ params: { id: post.id }, props: { post }, }))}
const { post } = Astro.propsconst { Content } = await render(post)---
<Layout title="{post.data.title}"> <h1>{post.data.title}</h1> <p>发布日期:{post.data.publish_date.toLocaleDateString()}</p> <p>标签:{post.data.tags.join(" ")}</p> <article> <content /> </article></Layout>列出文章入口链接
在哪里列都行,这里选择在首页列。
---import Layout from "@/layouts/main.astro"import { getCollection } from "astro:content"
const posts = await getCollection("blog")const sorted_posts = posts.sort( (a, b) => b.data.publish_date.valueOf() - a.data.publish_date.valueOf())---
<Layout> <div> <ul> {sorted_posts.map((post) => ( <li> <a href={`/posts/${post.id}`}>{post.data.title}</a> <small class="ml-4"> {post.data.publish_date.toLocaleDateString()} </small> </li> ))} </ul> </div></Layout>至此,Astro 博客的核心已经搭建完毕!
更多配置
- 排版样式系统:可用
shadcn的typeset。 - 代码复制按钮:可用
astro-expressive-code。