Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import markdown files as strings in Next.js

How can I import markdown files as strings in Next.js to work on client and server side?

like image 247
Romel Pérez Avatar asked Dec 23 '17 17:12

Romel Pérez


People also ask

What is MDX in next JS?

js by integrating MDX. "What is MDX?" You might ask me. Well... MDX is more or less like the markdown files we always see in GitHub repositories. MDX brings this flexibility into a markdown file by allowing you to literally write or import JavaScript (React) components into your articles.

Can I use require in next JS?

To recap, in a typical javascript framework (such as Gatsby or Next. js) project structure, both the require and import statements can be used inside the src directory as those files are to be transformed, compiled, and bundled using Babel and Webpack later in the build process for production.


1 Answers

You can configure your Next.js webpack loaders to load markdown files and return them as strings, for example:

docs/home.md

# Home

This is my **awesome** home!

pages/index.js

import React from 'react';
import markdown from '../docs/home.md';

export default () => {
  return (
    <div>
      <pre>{markdown}</pre>
      <small><i>Import and render markdown using Next.js</i></small>
    </div>
  );
};

package.json

{
  "name": "example",
  "version": "1.0.0",
  "scripts": {
    "dev": "next",
    "build": "next build",
    "start": "next start"
  },
  "dependencies": {
    "file-loader": "^1.1.6",
    "next": "^4.2.1",
    "raw-loader": "^0.5.1",
    "react": "^16.2.0",
    "react-dom": "^16.2.0"
  }
}

next.config.js

module.exports = {
  webpack: (config) => {
    return Object.assign({}, config, {
      externals: Object.assign({}, config.externals, {
        fs: 'fs',
      }),
      module: Object.assign({}, config.module, {
        rules: config.module.rules.concat([
          {
            test: /\.md$/,
            loader: 'emit-file-loader',
            options: {
              name: 'dist/[path][name].[ext]',
            },
          },
          {
            test: /\.md$/,
            loader: 'raw-loader',
          }
        ]),
      }),
    });
  }
};

When running:

$ npm run dev

Something like this would appear:

example preview

With the markdown string you can do whatever you would like. For example, process it with marksy.

like image 89
Romel Pérez Avatar answered Oct 05 '22 11:10

Romel Pérez