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

使用Chart.js开发React图表组件包时Rollup打包后出现构造函数错误

问题:Rollup打包Chart.js组件后引用报错Chart__default.default is not a constructor

开发基于Chart.js的React图表组件包,在Storybook中调试正常,但通过Rollup打包后,在其他项目引用时出现错误:

Chart__default.default is not a constructor

调试发现导入的Chart变量为文件路径而非Chart对象。

组件代码

import React, { FC } from 'react'
import Chart, { ChartOptions, ChartData } from 'chart.js/auto'
import { faker } from '@faker-js/faker'

const ChartElement: FC = () => {
  const getChartImage = () => {
    const canvas = document.createElement('canvas')
    canvas.width = 500
    canvas.height = 400
    const ctx = canvas.getContext('2d')

    if (!ctx) {
      return undefined
    }

    const options: ChartOptions = {
      responsive: false,
      animation: false,
      plugins: {
        legend: {
          position: 'top' as const
        },
        title: {
          display: true,
          text: 'Chart.js Line Chart'
        }
      }
    }
    const labels = ['January', 'February', 'March', 'April', 'May', 'June', 'July']

    const data:ChartData = {
      labels,
      datasets: [
        {
          label: 'Dataset 1',
          data: labels.map(() => faker.number.int({ min: -1000, max: 1000 })),
          borderColor: 'rgb(255, 99, 132)',
          backgroundColor: 'rgba(255, 99, 132, 0.5)'
        },
        {
          label: 'Dataset 2',
          data: labels.map(() => faker.number.int({ min: -1000, max: 1000 })),
          borderColor: 'rgb(53, 162, 235)',
          backgroundColor: 'rgba(53, 162, 235, 0.5)'
        }
      ]
    }

    const myChart = new Chart(ctx, {
      type: 'line',
      options,
      data
    })

    // 获取图表的base64图片字符串
    const image = myChart.toBase64Image()
    console.log(image)
    return image
  }

  const chartImage = getChartImage()

  return (
        <div className='report-element-chart-line'>
          {chartImage &&
            <img src={chartImage}/>
          }
        </div>
  )
}

export default ChartElement

包的tsconfig.json

{
  "compilerOptions": {
    "outDir": "dist",
    "module": "esnext",
    "target": "es2016",
    "esModuleInterop": true,
    "lib": ["es6", "dom", "es2016", "es2017", "dom.iterable"],
    "sourceMap": true,
    "allowJs": true,
    "jsx": "react-jsx",
    "declaration": true,
    "strict": true,
    "moduleResolution": "node",
    "forceConsistentCasingInFileNames": true,
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strictNullChecks": true,
    "noErrorTruncation": true,
    "noUnusedLocals": false,
    "noUnusedParameters": false,
    "allowSyntheticDefaultImports": true
  },
  "include": [
    "src"
  ],
  "exclude": ["node_modules", "dist", "rollup.config.mjs"]
}

包的rollup.config.mjs

import sass from 'rollup-plugin-sass'
import typescript from 'rollup-plugin-typescript2'
import css from 'rollup-plugin-import-css'
import svg from 'rollup-plugin-svg'

import pkg from './package.json' assert { type: 'json' }

export default {
  input: 'src/index.tsx',
  output: [
    {
      file: pkg.main,
      format: 'cjs',
      exports: 'named',
      sourcemap: true,
      interop: 'compat',
      strict: false,
      libraryTarget: 'umd'
    }
  ],
  plugins: [
    sass({ insert: true }),
    typescript({ objectHashIgnoreUnknownHack: true }),
    css(),
    svg()
  ],
  external: ['react', 'react-dom', 'react/jsx-runtime']
}

解决方案

1. 配置Rollup解析Chart.js模块

先安装模块解析依赖:

npm install @rollup/plugin-node-resolve @rollup/plugin-commonjs --save-dev

修改rollup.config.mjs,添加插件并调整互操作配置:

import sass from 'rollup-plugin-sass'
import typescript from 'rollup-plugin-typescript2'
import css from 'rollup-plugin-import-css'
import svg from 'rollup-plugin-svg'
import resolve from '@rollup/plugin-node-resolve'
import commonjs from '@rollup/plugin-commonjs'

import pkg from './package.json' assert { type: 'json' }

export default {
  input: 'src/index.tsx',
  output: [
    {
      file: pkg.main,
      format: 'cjs',
      exports: 'named',
      sourcemap: true,
      interop: 'auto', // 替换为auto,自动处理模块互操作
      strict: false,
      libraryTarget: 'umd'
    }
  ],
  plugins: [
    resolve({ browser: true }), // 解析浏览器环境下的模块
    commonjs({
      include: 'node_modules/**',
      namedExports: {
        'chart.js/auto': ['default', 'ChartOptions', 'ChartData'] // 指定Chart.js的导出项
      }
    }),
    sass({ insert: true }),
    typescript({ objectHashIgnoreUnknownHack: true }),
    css(),
    svg()
  ],
  external: ['react', 'react-dom', 'react/jsx-runtime']
}

2. 修正Chart.js导入方式

如果上述配置仍有问题,可调整组件中的导入语句:

// 替换原导入逻辑
import * as ChartModule from 'chart.js/auto';
const Chart = ChartModule.default;
import { ChartOptions, ChartData } from 'chart.js/auto';

3. 补充ES模块导出支持

在package.json中添加module字段,同时让Rollup输出ES模块格式:

{
  "main": "dist/index.js",
  "module": "dist/index.esm.js"
}

更新rollup.config.mjs的output配置:

output: [
  {
    file: pkg.main,
    format: 'cjs',
    exports: 'named',
    sourcemap: true,
    interop: 'auto',
    strict: false,
    libraryTarget: 'umd'
  },
  {
    file: pkg.module,
    format: 'es',
    sourcemap: true
  }
]

问题原因

该错误源于Rollup未正确解析Chart.js的ES模块导出,导致导入的Chart变量被错误识别为模块路径而非构造函数。Chart.js采用ES模块规范,而Rollup打包CommonJS/UMD格式时,需要额外配置处理模块互操作性,确保导出的构造函数能被正确识别。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.30 04:54:56