Nextjs博客重构记录

Mdx渲染markdown文章

    

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import fs from "fs";
import { join } from "path";
import matter from "gray-matter";
const postsDir = join(process.cwd(), "posts");

type MetaData = {
title: string;
date: Date;
updated: Date;
tags?: string[];
categories?: string[];
cover: string;
descr?: string;
draft?: boolean;
};

export function getPostBySlug(slug: string) {
const realSlug = slug.replace(/\.md$/, "");
const fullPath = join(postsDir, `${realSlug}.md`);
const fileContents = fs.readFileSync(fullPath, "utf8");
const { data, content, excerpt } = matter(fileContents, { excerpt: true, });
const meta = { ...data } as MetaData;
return { slug: realSlug, meta, content, excerpt };
}

export function getAllPosts() {
const slugs = fs.readdirSync(postsDir);
const posts = slugs.map((slug) => getPostBySlug(slug)).filter((c) => !/\.draft$/.test(c.slug));
return posts.sort((a, b) => +b.meta.date - +a.meta.date);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
import type { MDXComponents } from 'mdx/types'
// import Button from '@/components/tag_plugins/button'

export function useMDXComponents(components: MDXComponents): MDXComponents {
return {
...components,
h1: (props) => <h1 className="text-3xl font-bold">{props.children}</h1>,
h2: (props) => <h2 className='text-2xl font-bold'>{props.children}</h2>,
h3: (props) => <h3 className='text-xl font-bold'>{props.children}</h3>,
h4: (props) => <h4 className='text-lg font-bold'>{props.children}</h4>,
h5: (props) => <h5 className='text-base font-bold'>{props.children}</h5>,
h6: (props) => <h6 className='text-sm font-bold'>{props.children}</h6>,
// Button,
}
}