拾光笔记
← 全部文章

用 Next.js 搭建极简个人博客

约 1 分钟阅读前端

这篇文章记录我搭建这个博客的过程,包含技术选型、目录结构与核心实现。

技术选型

依赖 用途
next 应用框架(App Router)
tailwindcss 样式方案(v4,CSS 配置式)
gray-matter 解析 Markdown 的 frontmatter
remark + remark-gfm Markdown 解析与 GFM 扩展
rehype-pretty-code + shiki 代码高亮

读取并渲染文章

文章以 Markdown 形式存放在 content/posts 目录,通过 Node 的 fs 在构建时读取:

import fs from "fs";
import path from "path";
import matter from "gray-matter";
 
const postsDirectory = path.join(process.cwd(), "content", "posts");
 
export function getAllPosts() {
  return fs
    .readdirSync(postsDirectory)
    .filter((f) => f.endsWith(".md"))
    .map((file) => {
      const raw = fs.readFileSync(path.join(postsDirectory, file), "utf8");
      const { data } = matter(raw);
      return { slug: file.replace(/\.md$/, ""), ...data };
    });
}

渲染 Markdown 为 HTML

使用 unified 流水线,把 Markdown 转成 HTML 并加上语法高亮:

const processor = remark()
  .use(remarkGfm)
  .use(remarkRehype, { allowDangerousHtml: true })
  .use(rehypePrettyCode, { theme: "github-dark" })
  .use(rehypeStringify);

启动项目

npm install
npm run dev

打开 http://localhost:3000 即可预览。

小结

Next.js 的静态生成能力非常适合博客这类内容型网站。把文章当作文件管理,配合 Git 就能实现版本化,简单又可靠。

评论功能尚未开启。若想启用,请在 src/lib/site.ts 中配置 Giscus(步骤见 docs/DEPLOYMENT.md)。