React-Markdown Error: Must use import to load ES Module:

I try to install react-markdown to my nextjs project, but getting instantly following error when I try to use it.

My Code:

      import React from 'react'

import ReactMarkdown from 'react-markdown'

export function Markdown({ markdown }: { markdown: string }) {
  return (
    <article className="prose-sm">
      <ReactMarkdown>{markdown}</ReactMarkdown>
    </article>
  )
}

The error message:

      Error: Must use import to load ES Module: /Users/username/Projects/mono/node_modules/react-markdown/index.js
require() of ES modules is not supported.
require() of /Users/username/Projects/mono/node_modules/react-markdown/index.js from /Users/username/Projects/mono/dist/apps/webapp/.next/server/pages/_app.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from /Users/username/Projects/mono/node_modules/react-markdown/package.json

I am using following Versions: Node on v14.17.5 and yarn 1.22.11 and my current Nextjs version is ^12.6.2

1 ответ

I found following solution on Github. Here

You need to add next-transpile-modules to your next.config.js like following.

      // next.config.js

const withTM = require('next-transpile-modules')(['react-markdown']);

module.exports = withTM({
...
})

and you need to import react-markdown like: import ReactMarkdown from 'react-markdown/react-markdown.min';

Другие вопросы по тегам