Preface
The packages to be used:
- next Next.js framework
- next-mdx-remote handling and loading MDX content
- gray-matter parsing Markdown front matter
The repository for this tutorial:
https://github.com/nelsonlaidev/nextjs-mdx-blog
Demo
How to Create a Blog
First, we create the Next.js project with the following command:
Next, create the following files:
components/layout.jsx- Wrap all components in a container (optional, just the style)data/blog/*.mdx- Blog Articleslib/format-date.js- Format the date asMM DD, YYYYpages/blog/[slug].jsx- article page, using dynamic routes
Tree view
How to Handle Markdown Files
First, define root as the project root directory. The process.cwd() method returns the current working directory of the Node.js process.
Next, define POSTS_PATH as the directory where the article files are stored.
Then use fs to read the contents of that directory, that is, all the file names under data/blog.
Then write a function to remove the file extension, which will be used later.
The next step is to get the article content by slug.
Then you can get all the articles to be displayed in the home page.
Formatting Dates
Home Page
Article Page
This way, a simple blog is finished.
Useful Links
Thanks for reading.
Every little discovery leads to another.
Comments
Good ideas don’t end at the last line. What’s on your mind?