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

开发时ChartJS兼容Angular 5,但ng build构建失败求助

解决Angular 5中ng build时的TS2350错误

这个错误TS2350: Only a void function can be called with the 'new' keyword的核心问题是:TypeScript认为你用new调用的Chart不是可实例化的类,而是一个普通函数(甚至是返回void的函数)。结合你的Angular 5环境和代码,我整理了几个针对性的修复方案:

1. 降级到兼容的chart.js版本

Angular 5属于早期版本,和chart.js 3.x及以上版本兼容性极差——chart.js 3.x重构了API和导入逻辑,会导致TypeScript无法识别Chart作为构造函数。你需要降级到chart.js 2.x版本:

npm uninstall chart.js
npm install chart.js@2.9.4 --save

2. 安装匹配的类型定义

为了让TypeScript正确识别Chart的类型,需要安装和chart.js 2.x对应的@types/chart.js:

npm install @types/chart.js@2.9.37 --save-dev

3. 修正组件中的导入语句

确保你在组件里导入的是正确的Chart类,而非默认导出的函数:

// 正确的导入方式
import { Chart } from 'chart.js';

避免使用import Chart from 'chart.js';这种默认导入,这在chart.js 2.x环境下会导致TypeScript误判类型。

4. 确保DOM引用的有效性

你代码中的this.htmlRef必须是有效的Canvas DOM元素引用,建议用@ViewChild获取,并在视图初始化完成后再实例化图表:

import { Component, ViewChild, ElementRef, AfterViewInit } from '@angular/core';
import { Chart } from 'chart.js';

@Component({
  // 组件元数据
})
export class BrandDetailsComponent implements AfterViewInit {
  @ViewChild('chartCanvas') chartCanvas: ElementRef;
  chart: Chart;

  ngAfterViewInit() {
    const chartValues = [/* 你的数据数组 */];
    const chartLabels = [/* 你的标签数组 */];
    const COLORS = [/* 颜色配置数组 */];

    this.chart = new Chart(this.chartCanvas.nativeElement, {
      type: 'doughnut',
      data: {
        datasets: [{
          data: chartValues,
          backgroundColor: COLORS,
          hoverBackgroundColor: []
        }],
        labels: chartLabels
      },
      options: {
        cutoutPercentage: 20,
        responsive: true
        // 其他配置项
      }
    });
  }
}

同时在模板中对应添加Canvas元素:

<canvas #chartCanvas></canvas>

完成以上步骤后,重新执行ng build应该就能解决这个错误了。

内容的提问来源于stack exchange,提问作者Ing. Luca Stucchi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:26:15