The packages to be used:
The repository for this tutorial:
https://github.com/tszhong0411/nextjs-mdx-blog
Online
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 Articles
lib/format-date.js
- Format the date as MM DD, YYYY
pages/blog/[slug].jsx
- article page, using dynamic routes
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.
This way, a simple blog is finished.