将要使用的包:
本教程的仓库:
https://github.com/tszhong0411/nextjs-mdx-blog
在线演示
首先,我们使用以下命令创建一个 Next.js 项目:
yarn create next-app nextjs-mdx-blog
接下来,创建以下文件:
components/layout.jsx
—— 用于包裹所有组件的容器(可选,仅用于样式)
data/blog/*.mdx
—— 博客文章
lib/format-date.js
—— 将日期格式化为 MM DD, YYYY
pages/blog/[slug].jsx
—— 文章页面,采用 动态路由
首先,声明 const root
—— 表示根目录,process.cwd()
方法返回 Node.js 进程当前的工作目录。
const root = process.cwd()
接下来,定义变量 POSTS_PATH
,表示文章文件存放的路径。
import path from 'path'
const POSTS_PATH = path.join(root, 'data', 'blog')
// 输出示例:A:/nextjs-mdx-blog/data/blog
然后使用 fs
读取该目录下的所有文件名,也就是 data/blog
下的所有文件。
import fs from 'fs'
export const allSlugs = fs.readdirSync(POSTS_PATH)
// 输出示例:['markdown.mdx', 'nextjs.mdx', 'react.mdx']
接下来编写一个函数,用于移除文件扩展名,后续会使用到。
export const formatSlug = (slug) => slug.replace(/\.mdx$/, '')
/**
* 示例:formatSlug('markdown.mdx')
* 输出:'markdown'
*/
下一步是通过 slug 获取文章内容。
export const getPostBySlug = async (slug) => {
const postFilePath = path.join(POSTS_PATH, `${slug}.mdx`)
// 输出示例:A:/nextjs-mdx-blog/data/blog/slug.mdx
const source = fs.readFileSync(postFilePath)
// 返回文件内容
const { content, data } = matter(source)
/*
* 示例:
* ---
* title: Hello
* slug: home
* ---
* <h1>Hello world!</h1>
*
* 返回:
* {
* content: '<h1>Hello world!</h1>',
* data: {
* title: 'Hello',
* slug: 'home'
* }
* }
*/
const mdxSource = await serialize(content)
// 对内容进行序列化处理(使用 next-mdx-remote)
const frontMatter = {
...data,
slug
}
// 同时将 slug 放入 front matter,后续会使用到
return {
source: mdxSource,
frontMatter
}
}
然后,你可以获取所有文章,以便在首页展示。
export const getAllPosts = () => {
const frontMatter = []
allSlugs.forEach((slug) => {
const source = fs.readFileSync(path.join(POSTS_PATH, slug), 'utf-8')
const { data } = matter(source)
frontMatter.push({
...data,
slug: formatSlug(slug),
date: new Date(data.date).toISOString()
})
})
return frontMatter.sort((a, b) => dateSortDesc(a.date, b.date))
}
// 按日期降序排序
const dateSortDesc = (a, b) => {
if (a > b) return -1
if (a < b) return 1
return 0
}
export const formatDate = (date) =>
new Date(date).toLocaleDateString('en', {
year: 'numeric',
month: 'long',
day: 'numeric'
})
/*
* 示例:formatDate('2022-08-21T00:00:00Z')
* 输出:'August 21, 2022'
*/
import { formatDate } from '../lib/format-date'
import { getAllPosts } from '../lib/mdx'
import Link from 'next/link'
export default function Home({ posts }) {
return (
<>
<h1 className='mb-8 text-6xl font-bold'>Blog</h1>
<hr className='my-8' />
<ul className='flex flex-col gap-3'>
{posts.map(({ slug, title, summary, date }) => (
<li key={slug}>
<Link href={`/blog/${slug}`}>
<a className='block rounded-lg border border-solid border-gray-300 p-6 shadow-md'>
<div className='flex justify-between'>
<h2>{title}</h2>
<time dateTime={date}>{formatDate(date)}</time>
</div>
<p className='mt-4'>{summary}</p>
</a>
</Link>
</li>
))}
</ul>
</>
)
}
// 使用 getStaticProps 获取所有文章
export const getStaticProps = async () => {
const posts = getAllPosts()
return {
props: {
posts
}
}
}
import { formatDate } from '../../lib/format-date'
import { allSlugs, formatSlug, getPostBySlug } from '../../lib/mdx'
import { MDXRemote } from 'next-mdx-remote'
export default function Blog({ post }) {
const { title, date } = post.frontMatter
return (
<div>
<h1 className='mb-2 text-6xl font-bold'>{title}</h1>
<time dateTime={date} className='text-lg font-medium'>
{formatDate(date)}
</time>
<hr className='my-8' />
<article className='prose max-w-none'>
<MDXRemote {...post.source} />
</article>
</div>
)
}
export const getStaticProps = async ({ params }) => {
const post = await getPostBySlug(params.slug)
return {
props: {
post
}
}
}
export const getStaticPaths = async () => {
const paths = allSlugs.map((slug) => ({
params: {
slug: formatSlug(slug)
}
}))
/*
* paths 输出示例:
* [
* { params: { slug: 'markdown' } },
* { params: { slug: 'nextjs' } },
* { params: { slug: 'react' } }
* ]
*/
return {
paths,
fallback: false
}
}
这样,一个简单的博客就完成了。