在使用 D3.js 7.0.0 和 Next.js 11.0.1 时,如何解决“[ERR_REQUIRE_ESM]:必须使用导入来加载 ES 模块”?

问题描述 投票:0回答:4

尝试将 D3 与 Next.js 结合使用时,在将 D3.js v7.0.0 与 Next.js v11.0.1 结合使用时,我无法克服此错误。:

[ERR_REQUIRE_ESM]:必须使用 import 来加载 ES 模块

  • 我尝试了
    next-transpile-modules
    但没有运气
  • 我有 D3.js v7.0.0 可以使用
    create-react-app
    但我需要 D3 可以与 Next.js v11.0.1 一起使用

我使用

npm i d3
安装了 D3.js。我正在使用
import * as d3 from "d3"
导入。使用 Node v15.8.0 和 React v17.0.2

javascript node.js d3.js next.js node-modules
4个回答
2
投票

如果您只需要从 ES6+ 功能“导入”,只需在

package.json
文件中添加 'type': 'module' 即可。否则,请使用 babel 为您的应用程序启用所有 ES6+ 功能。


2
投票

从 v12 开始,Next.js 原生支持 ES 模块。因此,如果有人遇到此问题,只需升级您的 Next.js 版本即可。现在完全支持 D3 和其他仅提供 ESM 入口点的软件包,无需转译它们。

参考:https://nextjs.org/blog/next-12#es-modules-support-and-url-imports

此支持在 Next.js v11.1 中处于实验阶段,可以使用以下配置启用:

// next.config.js
module.exports = {
  // Prefer loading of ES Modules over CommonJS
  experimental: { esmExternals: true }
}

参考:https://nextjs.org/blog/next-11-1#es-modules-support


1
投票

对于新版本,请使用

'loose'
选项

module.exports = {
    // Prefer loading of ES Modules over CommonJS
    experimental: { esmExternals: 'loose' }
}

0
投票

这非常奇怪,因为只有在干净地重新启动项目并刷新浏览器时才会出现该错误。当我开发时,一切都很好 - 可能是因为 HMR,它动态加载组件。

我的例子的解决方案是使用动态加载,错误消息也暗示了这一点:

Server Error
Error: require() of ES Module ... from ... not supported.
Instead change the require of index.js in ... to a dynamic import() which is
available in all CommonJS modules.

解决方案

// before
import { ResponsiveBar } from '@nivo/bar'

// after
const ResponsiveBar = dynamic(() => import('@nivo/bar').then(m => m.ResponsiveBar), {
  loading: () => <p>Loading...</p>,
  ssr: false,
})
© www.soinside.com 2019 - 2024. All rights reserved.