簡體   English   中英

錯誤:使用帶有 next.js(和打字稿)的重新圖表時,不支持 ES 模塊的 require()

[英]Error: require() of ES module is no supported when using recharts with next.js (and typescript)

我看到了一些此類問題,但沒有一個真正解決我的問題。 我正在使用next.js (使用打字稿)開發一個網絡應用程序。 在我的應用程序中使用recharts ,但編譯失敗並出現此錯誤:

Error: Must use import to load ES Module: project_path\node_modules\d3-shape\src\index.js
require() of ES modules is not supported.
require() of project_path\node_modules\d3-shape\src\index.js from project_path\node_modules\recharts\lib\shape\Symbols.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 project_path\node_modules\d3-shape\package.json.

現在,我使用的是 next.js 12,它開箱即用地支持 ES 模塊,不需要額外的配置。 據我了解,問題是d3-shape現在作為 ESM 導入,但是使用它的recharts仍然require它而不是導入它(這是真的,“complied” recharts package 確實使用require()

所以問題不是我的應用程序,而是 recharts 導入 d3-shapes 的方式,但我該如何解決呢? 我是唯一一個受苦的人,這是沒有意義的。

我想我可以 fork recharts並確保它將 d3-shapes 導入為 esm 模塊(將type: "module"添加到 package.json 文件),但這非常難看。

有人有什么想法嗎? 我真的不想 go 並使用其他圖表包...

https://github.com/recharts/recharts/issues/2918

在相應的鏈接上談論同樣的問題。

將 package 版本的 recharts 降級到“2.1.12”將解決問題。 就我而言,它已經解決了。

動態導入似乎解決了這個問題。

import dynamic from "next/dynamic";

const Chart = dynamic(() => import("features/dashboard/Chart"), { ssr: false });

如果您到達此處時出現相同的錯誤但使用 Remix Run,請參閱文檔的這一部分: https://remix.run/docs/en/v1/pages/gotchas#importing-esm-packages

這是我的配置文件看起來如何編譯:

//in remix.config.js
/** @type {import('@remix-run/dev').AppConfig} */
module.exports = {
  ignoredRouteFiles: ["**/.*"],
  serverDependenciesToBundle: [
    "recharts",
    "d3-shape",
    "d3-scale",
    "d3-path",
    "d3-array",
    "d3-time",
    "d3-format",
    "d3-interpolate",
    "d3-time-format",
    "d3-color",
    "internmap",
  ],
};

暫無
暫無

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

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