【问题标题】:Error: Must use import to load ES Module: D:\node_modules\react-markdown\index.js require() of ES modules is not supported错误:必须使用 import 加载 ES 模块:不支持 ES 模块的 D:\node_modules\react-markdown\index.js require()
【发布时间】:2021-10-30 15:05:04
【问题描述】:

目前我正在使用"react": "17.0.2" 并且我已经通过npm i react-markdown 安装了"react-markdown": "^7.0.1" 我正在使用this package 来显示我从我的Strapi CMS 获取的富文本。我已经使用以下代码来显示内容:

import ReactMarkdown from "react-markdown";

export default function name({ posts }) {
  return (
    <>
      <div>
        <div>
          {posts.Title}
        </div>
      </div>
      <div>
        <ReactMarkdown source={posts.Content} escapeHtml={false} />
      </div>
    </>
  );
}

export async function getStaticProps() {
  const res = await fetch("http://localhost:1337/blogs");
  const posts = await res.json();

  return {
    props: { posts },
  };
}

但是当我运行它时,它给了我以下错误:

我正在使用节点 v14.17.0 并尝试添加 "type": "module"

我的 package.json:

{
  "name": "passportlegacy",
  "version": "0.1.0",
  "private": true,
  "scripts": {
    "dev": "next dev",
    "build": "next build",
    "start": "next start",
    "lint": "next lint"
  },
  "dependencies": {
    "axios": "^0.21.1",
    "babel-plugin-inline-react-svg": "^2.0.1",
    "next": "11.0.1",
    "next-images": "^1.8.1",
    "react": "17.0.2",
    "react-dom": "17.0.2",
    "react-map-gl": "^6.1.16",
    "react-markdown": "^7.0.1",
  },
  "devDependencies": {
    "@svgr/webpack": "^5.5.0",
    "@types/react": "17.0.16",
    "eslint": "7.32.0",
    "eslint-config-next": "11.0.1",
    "typescript": "4.3.5"
  }
}

【问题讨论】:

标签: javascript reactjs npm markdown strapi


【解决方案1】:

我通过将 react-markdown 降级到版本 6 解决了这个问题。

在 react-markdown 的第 7 版中,他们只迁移到了 esm。有一个关于 here 含义的解释,但截至 2021 年 10 月,Jest 似乎仍然只有 experimental support 用于纯 ESM 模块。我无法让它在我的项目中工作,并且 react-markdown 版本 6 工作现在还好。

【讨论】:

    【解决方案2】:

    Node 当前正在将您的 .js 文件视为 CommonJS。您需要告诉 Node 将其视为 ES 模块。

    尝试在您的package.json 文件中添加"type": "module"

    您可以将其放置在顶层的任何位置。例如:

    {
      "name": "passportlegacy",
      "version": "0.1.0",
      "type": "module",
      "private": true,
      "scripts": {
        ...
      }
      ...
    }
    

    更多信息:package.json and file extensions - Node.js 14.x LTS documentation

    【讨论】:

    • 我应该将“type”:“module”放在我的 package.json 中的什么位置?
    • 您可以将其放置在顶层的任何位置。我在答案中添加了一个示例。
    猜你喜欢
    • 2022-11-11
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 2020-09-06
    • 2022-11-18
    • 2020-11-10
    • 2022-11-09
    • 2021-12-28
    相关资源
    最近更新 更多