← Quay lại blog
·1 min read

Xây Blog Với MDX và Next.js

MDX cho phép viết JSX bên trong Markdown — hoàn hảo cho technical blog.

Tại Sao MDX?

  • Viết content bằng Markdown quen thuộc
  • Nhúng React components khi cần
  • Syntax highlighting với Shiki
  • Lưu trong Git repo, không cần CMS

Cài Đặt

npm install next-mdx-remote gray-matter
npm install rehype-pretty-code shiki rehype-slug remark-gfm

Cấu Trúc Thư Mục

content/
└── posts/
    ├── hello-world.mdx
    ├── nextjs-guide.mdx
    └── react-tips.mdx

Parse Frontmatter

import matter from 'gray-matter';
 
const { data, content } = matter(fileContents);
// data = { title, description, date, tags }
// content = MDX string

Compile MDX

import { compileMDX } from 'next-mdx-remote/rsc';
 
const { content } = await compileMDX({
  source: rawMDX,
  options: {
    mdxOptions: {
      remarkPlugins: [remarkGfm],
      rehypePlugins: [
        rehypeSlug,
        [rehypePrettyCode, { theme: 'one-dark-pro' }],
      ],
    },
  },
});

Custom Components

Bạn có thể truyền custom components vào MDX:

const components = {
  img: (props) => <Image {...props} className="rounded-lg" />,
  a: (props) => <Link {...props} className="text-primary hover:underline" />,
};

Kết Quả

Một blog nhanh, SEO-friendly, với full control over content và styling.

Nhận bài viết mới

Bài viết mới gửi thẳng vào inbox. Không spam, unsubscribe bất cứ lúc nào.