返回列表

Next.js + MDX 博客搭建指南

3 分钟阅读

title: "Next.js + MDX 博客搭建指南" date: "2024-01-16" excerpt: "详细介绍如何使用 Next.js 和 MDX 搭建一个功能完整的个人博客系统。" tags: ["教程", "Next.js", "MDX", "博客"]

Next.js + MDX 博客搭建指南

在这篇文章中,我将详细介绍如何使用 Next.js 和 MDX 搭建一个功能完整的个人博客系统。

项目初始化

首先,我们需要创建一个新的 Next.js 项目:

npx create-next-app@latest my-blog --typescript --tailwind --eslint
cd my-blog

安装依赖

安装 MDX 相关的依赖包:

npm install @next/mdx @mdx-js/react @mdx-js/loader gray-matter date-fns

配置 Next.js

next.config.js 中添加 MDX 支持:

const withMDX = require('@next/mdx')({
  extension: /\.mdx?$/,
  options: {
    remarkPlugins: [],
    rehypePlugins: [],
  },
})

const nextConfig = {
  pageExtensions: ['js', 'jsx', 'mdx', 'ts', 'tsx'],
  experimental: {
    mdxRs: true,
  },
}

module.exports = withMDX(nextConfig)

创建内容管理

使用 gray-matter 解析 MDX 文件的 frontmatter:

import fs from 'fs'
import path from 'path'
import matter from 'gray-matter'

export function getBlogPosts() {
  const postsDirectory = path.join(process.cwd(), 'content/blog')
  const fileNames = fs.readdirSync(postsDirectory)
  
  return fileNames
    .filter(fileName => fileName.endsWith('.mdx'))
    .map(fileName => {
      const slug = fileName.replace(/\.mdx$/, '')
      const fullPath = path.join(postsDirectory, fileName)
      const fileContents = fs.readFileSync(fullPath, 'utf8')
      const { data, content } = matter(fileContents)
      
      return {
        slug,
        title: data.title,
        date: data.date,
        excerpt: data.excerpt,
        content,
        tags: data.tags || [],
      }
    })
}

路由配置

使用 Next.js 13+ 的 App Router 创建动态路由:

// app/blog/[slug]/page.tsx
export async function generateStaticParams() {
  const posts = getBlogPosts()
  return posts.map((post) => ({
    slug: post.slug,
  }))
}

export default async function BlogPost({ params }: { params: { slug: string } }) {
  const post = getBlogPost(params.slug)
  
  return (
    <article>
      <h1>{post.title}</h1>
      <div dangerouslySetInnerHTML={{ __html: post.content }} />
    </article>
  )
}

样式设计

使用 Tailwind CSS 构建响应式界面:

export default function BlogList({ posts }: { posts: BlogPost[] }) {
  return (
    <div className="grid gap-8 md:grid-cols-2 lg:grid-cols-3">
      {posts.map((post) => (
        <article key={post.slug} className="bg-white rounded-lg shadow-md p-6">
          <h3 className="text-xl font-semibold mb-3">{post.title}</h3>
          <p className="text-gray-600">{post.excerpt}</p>
        </article>
      ))}
    </div>
  )
}

部署

项目可以部署到 Vercel、Netlify 等平台:

npm run build
npm run start

总结

通过这个指南,你应该能够搭建一个基本的 Next.js + MDX 博客系统。这个系统具有以下优势:

  • 🚀 快速开发和部署
  • 📱 响应式设计
  • 🔍 SEO 友好
  • 🎨 灵活的内容创作
  • 📊 优秀的性能表现

希望这个指南对你有所帮助!如果有任何问题,欢迎在评论区讨论。