Preface
The packages to be used:
- next Next.js framework
- next-mdx-remote handling and loading mdx content
- gray-matter parse the front matter in markdown
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 file:
components/layout.jsx- Wrap all components in a container (optional, just the style)date/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 const root - the root directory, and the process.cwd() method returns the current working directory of the Node.js process.
Another variable POSTS_PATH for the path 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 Date
Home page
Article Page
This way, a simple blog is finished.
