簡體   English   中英

錯誤:必須使用 import 加載 ES 模塊:不支持 ES 模塊的 D:\\node_modules\\react-markdown\\index.js require()

[英]Error: Must use import to load ES Module: D:\node_modules\react-markdown\index.js require() of ES modules is not supported

目前我正在使用"react": "17.0.2"並且我已經通過 npm 安裝了"react-markdown": "^7.0.1" npm i react-markdown我正在使用這個包來顯示我的富文本m 從我的 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"
  }
}

我通過將 react-markdown 固定到版本 6 來解決這個問題。

使用 react-markdown 的第 7 版,他們只遷移到 ESM。 這里有一個關於這意味着什么的解釋,但截至 2021 年 10 月,Jest(版本 27)似乎仍然只對純 ESM 模塊提供實驗性支持。我無法讓它在我的項目和 react-markdown 版本 6 中工作現在工作正常。

我認為 Jest 的下一個主要版本(版本 28)將支持 ESM。

Node 當前將您的.js<\/code>文件視為 CommonJS。 您需要告訴 Node 將其視為 ES 模塊。

嘗試在package.json<\/code>文件中添加"type": "module"<\/code> 。

您可以將其放置在頂層的任何位置。 例如:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM