javascriptreactjsmarkdownnext.js

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?


Solution

  • 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.