You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NextJs中使用React-gauge-chart遇ES Module require()不支持错误求助

解决react-gauge-chart导入d3时的require()/ES模块冲突问题

这个错误是因为react-gauge-chart的CommonJS构建版本里用了require()去导入ES模块格式的d3,而Node.js/打包工具不允许这种跨模块格式的同步导入。下面是几种可行的解决办法:

1. 升级react-gauge-chart到最新版本

官方大概率已经修复了这个模块导入格式不兼容的问题,直接执行更新命令:

npm update react-gauge-chart
# 或者用yarn
yarn upgrade react-gauge-chart

2. 配置打包工具转译d3模块

如果升级后问题还存在,让打包工具把d3转译为CommonJS格式:

Webpack配置示例

在webpack.config.js中添加规则,转译d3的代码:

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        include: /node_modules\/d3/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  }
};

Next.js配置示例

在next.config.js中把d3和react-gauge-chart加入转译列表:

const nextConfig = {
  transpilePackages: ['d3', 'react-gauge-chart'],
}

module.exports = nextConfig

3. 手动修改react-gauge-chart的导入代码(不推荐)

如果以上方法都不行,临时修改依赖包的代码(注意:依赖更新后会被覆盖):
找到/node_modules/react-gauge-chart/dist/GaugeChart/index.js里的const d3 = require('d3');,替换为动态import:

import('d3').then(d3 => {
  // 把原来依赖d3的逻辑放到这个回调里
});

内容的提问来源于stack exchange,提问作者Nooblantis District

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.31 00:57:26