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

Chart.js中Chart.register is not a function错误排查求助

问题:本地运行正常,打包组件时出现 Chart.register is not a function 错误

本地运行应用时一切正常,但将其打包为组件时出现错误提示:Chart.register is not a function,恳请各位提供帮助。

我的代码

import React, { useEffect } from 'react'
import { Chart, CategoryScale, LinearScale, BarElement } from 'chart.js'
import { Bar } from 'react-chartjs-2'

Chart.register(CategoryScale, LinearScale, BarElement)
function SpectrumAllocation() {
  const options = {
    indexAxis: 'y',
    elements: {
      bar: {
        borderWidth: 2
      }
    },
    responsive: true,
    plugins: {
      legend: {
        position: 'right'
      },
      title: {
        display: true,
        text: 'Chart.js Horizontal Bar Chart'
      }
    }
  }

  const labels = [
    'January',
    'February',
    'March',
    'April',
    'May',
    'June',
    'July'
  ]

  const data = {
    labels,
    datasets: [
      {
        label: 'Dataset 1',
        data: [12, 23, 34, 45, 56],
        borderColor: 'rgb(255, 99, 132)',
        backgroundColor: 'rgba(255, 99, 132, 0.5)'
      },
      {
        label: 'Dataset 2',
        data: [12, 23, 34, 45, 56],
        borderColor: 'rgb(53, 162, 235)',
        backgroundColor: 'rgba(53, 162, 235, 0.5)'
      }
    ]
  }

  return <Bar options={options} data={data} />
}

export default SpectrumAllocation

已尝试的解决方案

  • 从"chart.js/auto"导入Chart
  • 从"chart.js"导入{Chart}
  • 降级chart.js版本

以上方案均未解决问题。

内容的提问来源于stack exchange,提问作者Prajwal Jaiswal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 20:52:24