Import Markdown Files and Serve Its Content in Next.js

Import Markdown Files in Next.js

As @arunoda (Next.js founder) said Next.js does not support importing markdown files yet. But you can configure the Next.js webpack loaders to load raw-loader modules and import markdown files and return them as strings.

Let get started!

Open the terminal, run the command below to install raw-loader and react-markdown modules (noted: use react-markdown to renders markdown as pure React components):

1
2
3
npm install --save raw-loader

npm install --save react-markdown

Create next.config.js file with content below:

next.config.js
1
2
3
4
5
6
7
8
9
10
11
12
module.exports = {
  webpack: (config) => {
    config.module.rules.push(
      {
        test: /\.md$/,
        use: 'raw-loader'
      }
    )

    return config
  },
}

Create docs/about.md file with content below:

about.md
1
2
3
# About

Welcome to **GeeKhmer**!

Create pages/about.js file with content below:

about.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
import React from 'react'
import ReactMarkdown from 'react-markdown'

export default class extends React.Component {
  static async getInitialProps({ req }) {
    const content = await require(`../docs/about.md`)
    return { content }
  }

  render() {
    return (
      <div>
        <ReactMarkdown source={this.props.content} />
      </div>
    )
  }
}

So far so good, That’s it!!! See ya!!! :)