error - unhandledRejection: Error: Not supported at Object.react-markdown

error - unhandledRejection: Error: Not supported at Object.react-markdown

目前我在我的 React 项目中使用 react-markdown 作为我的降价组件。除此之外,我还使用了 rehype-raw 和 remark-gfm。每当我 运行 项目时,我都会收到以下错误:

以下是我的package.json:

"dependencies": {
    "next": "11.1.2",
    "next-images": "^1.8.1",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    "react-markdown": "^7.0.1",
    "rehype-raw": "^6.1.0",
    "remark-gfm": "^2.0.0",
  },

我的组件:

import ReactMarkdown from "react-markdown";
import styles from "../styles/Home.module.css";
import remarkGfm from "remark-gfm";
import rehypeRaw from "rehype-raw";

export default function Home({ posts }) {
  return (
     <main className={styles.main}>
        {posts &&
          posts.map((image) => (
            <div style={{ height: "100%" }}>
              <ReactMarkdown
                children={image.Content}
                rehypePlugins={[rehypeRaw]}
              />
            </div>
          ))}
      </main>
   );
}

日志中显示的错误:

我也遇到了类似的错误,然后我找到了这个解决方案:

https://github.com/vercel/next.js/issues/25454#issuecomment-903513941

ReactMarkdown 是一个 ESM 模块,这意味着它不能是 required,而是 imported。如果您的代码中实际上是 importing,则可能是转译器(例如:Babel)更改了它,因此出现了错误。所以这可能是错误的原因。

你可以做些什么来解决这个问题(在其他人提交的问题中也有描述):

  1. npm i next-transpile-modules

  2. next.config.js 中执行以下操作:

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

module.exports = withTM({
...restOfYourConfig
})
  1. 像这样导入 ReactMarkdown:import ReactMarkdown from 'react-markdown/react-markdown.min';

其他来源:

https://gist.github.com/sindresorhus/a39789f98801d908bbc7ff3ecc99d99c

https://nextjs.org/docs/messages/import-esm-externals

https://www.npmjs.com/package/next-transpile-modules