错误:将 recharts 与 next.js (和 typescript)一起使用时,不支持 ES 模块的 require()

Mic*_*ich 13 typescript es6-modules next.js recharts

我看到了一些此类问题,但没有一个真正解决我的问题。我正在使用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.
Run Code Online (Sandbox Code Playgroud)

现在,我使用 next.js 12,它支持开箱即用的 ES 模块,不需要额外的配置。据我了解,问题是d3-shape现在作为 ESM 导入,但是recharts使用它仍然require是它而不是导入它(这是真的,“complied”recharts 包确实使用require())

所以问题不在于我的应用程序,而是 recharts 导入 d3-shapes 的方式,但我该如何解决呢?我是唯一一个遭受这种痛苦的人,这是没有意义的。

我想我可以分叉recharts并确保它将 d3-shapes 作为 esm 模块导入(添加type: "module"到 package.json 文件),但这非常丑陋。

有人有什么想法吗?我真的不想去使用其他图表包......

小智 15

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

在相应的链接上谈论同样的问题。

将 recharts 的软件包版本降级到“2.1.12”即可解决问题。就我而言,它已解决。