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

Angular 9升级Chart.js至最新版遇问题,求版本兼容清单及解决办法

Angular 9 升级 Chart.js 问题解决方案

问题背景

使用Angular 9,当前集成Chart.js v2.9.4,升级至最新版本后出现模块解析错误:

ERROR in ./node_modules/chart.js/dist/chart.js 568:17
Module parse failed: Unexpected token (568:17)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
|     };
| class DatasetController {
>  static defaults = {};
|  static datasetElementType = null;
|  static dataElementType = null;

对应的柱状图组件代码:

bar-chart.component.html

<div class="chart-container">
      <canvas  id="MyChart" >{{ chart }}</canvas>
</div>

bar-chart.component.ts

import { Component, OnInit } from '@angular/core';
import { Chart } from 'chart.js';
@Component({
  selector: 'app-bar-chart',
  templateUrl: './bar-chart.component.html',
  styleUrls: ['./bar-chart.component.scss']
})
export class BarChartComponent implements OnInit {

  constructor() { }
  public chart: any;

  ngOnInit(): void {
    this.createChart();
  }

  createChart(){
  
    this.chart = new Chart("MyChart", {
      type: 'bar', //this denotes tha type of chart

      data: {// values on X-Axis
        labels: ['2022-05-10', '2022-05-11', '2022-05-12','2022-05-13',
                                 '2022-05-14', '2022-05-15', '2022-05-16','2022-05-17', ], 
           datasets: [
          {
            label: "Sales",
            data: ['467','576', '572', '79', '92',
                                 '574', '573', '576'],
            backgroundColor: 'blue'
          },
          {
            label: "Profit",
            data: ['542', '542', '536', '327', '17',
                                     '0.00', '538', '541'],
            backgroundColor: 'limegreen'
          }  
        ]
      },
      options: {
        aspectRatio:2.5
      }
      
    });
  }

}

解答

1. 能否升级至Chart.js最新版本

可以升级,但Chart.js v3+ 采用ES模块语法并使用了ES6+特性,Angular 9默认的webpack 4配置需调整才能适配,同时要修改组件代码以兼容新的API规范。

2. 版本兼容清单查看方式

  • 查看Chart.js官方文档的兼容性章节,会标注支持的JS环境语法版本;
  • 若使用Chart.js的Angular封装库(如ng2-charts),直接参考封装库README中的版本适配表;
  • 查看Chart.js npm包的peerDependencies字段,了解其依赖的环境版本范围;
  • Angular官方更新日志会标注各版本支持的JS语法特性,可对应Chart.js的要求判断兼容性。

3. 解决模块解析错误的步骤

错误原因是Chart.js v3+ 使用的类静态属性初始化语法未被Angular 9的webpack loader解析,按以下步骤修复:

步骤1:安装babel依赖

npm install @babel/core @babel/preset-env babel-loader --save-dev

步骤2:扩展webpack配置

  • 安装自定义webpack构建器:
    npm install @angular-builders/custom-webpack --save-dev
    
  • 在项目根目录创建extra-webpack.config.js:
    module.exports = {
      module: {
        rules: [
          {
            test: /\.js$/,
            exclude: /node_modules(?!\/chart.js)/,
            use: {
              loader: 'babel-loader',
              options: {
                presets: [['@babel/preset-env', { targets: "defaults" }]]
              }
            }
          }
        ]
      }
    };
    
  • 修改angular.json,替换构建器并添加自定义配置:
    在projects -> [你的项目名称] -> architect -> build和serve节点中,修改builder并添加customWebpackConfig:
    "builder": "@angular-builders/custom-webpack:browser",
    "options": {
      "customWebpackConfig": {
        "path": "./extra-webpack.config.js"
      },
      // 保留原有其他配置
    }
    

步骤3:调整组件代码适配Chart.js v3+

  • 更新导入方式,手动注册Chart.js组件:
    import { Chart, registerables } from 'chart.js';
    Chart.register(...registerables);
    
  • 将data数组改为数值类型(Chart.js v3+不再自动转换字符串为数值):
    datasets: [
      {
        label: "Sales",
        data: [467, 576, 572, 79, 92, 574, 573, 576],
        backgroundColor: 'blue'
      },
      {
        label: "Profit",
        data: [542, 542, 536, 327, 17, 0.00, 538, 541],
        backgroundColor: 'limegreen'
      }  
    ]
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.25 04:23:20