CanvasJS with Angular 11:你可能需要一个额外的加载器来处理这些加载器的结果

CanvasJS with Angular 11: You may need an additional loader to handle the result of these loaders

我尝试将 CanvasJS 用于 Angular 11 项目,但导入时出现错误:

Failed to compile.

./node_modules/canvasjs/src/charts/index.js 1:7
Module parse failed: Unexpected token (1:7)
File was processed with these loaders:
 * ./node_modules/@angular-devkit/build-angular/src/babel/webpack-loader.js
 * ./node_modules/@ngtools/webpack/src/ivy/index.js
You may need an additional loader to handle the result of these loaders.
> export SplineChart from '../charts/spline';
| export ColumnChart from '../charts/column';
| export StackedColumnChart from '../charts/stacked_column';

package.json :

"dependencies": {
  ...
  "canvasjs": "^1.8.3",
  ...
},
"devDependencies": {
  ...
  "@types/canvasjs": "^1.9.7",

我在组件中的导入看起来像这样(没有错误):

import * as CanvasJS from 'canvasjs';

我在 ngOnInit() 上初始化图表(示例代码):

ngOnInit(): void {
  let chart = new CanvasJS.Chart("chartContainer", {
    animationEnabled: true,
    exportEnabled: true,
    title: {
      text: "Basic Column Chart in Angular"
    },
    data: [{
      type: "column",
        dataPoints: [
          { y: 71, label: "Apple" },
          { y: 55, label: "Mango" },
          { y: 50, label: "Orange" },
          { y: 65, label: "Banana" },
          { y: 95, label: "Pineapple" },
          { y: 68, label: "Pears" },
          { y: 28, label: "Grapes" },
          { y: 34, label: "Lychee" },
          { y: 14, label: "Jackfruit" }
        ]
    }]
  });
  
  chart.render();
}

我错过了什么?

您使用的似乎是过时/非官方版本的 CanvasJS。按照以下步骤在您的 Angular 应用程序中添加 CanvasJS 图表。

  1. CanvasJS Download Page / commercial version from My Account Page下载正式版。

  2. 将 canvasjs.min.js 保存在应用程序文件夹中

  3. 导入库

    import * as CanvasJS from './canvasjs.min';
    
  4. 创建并呈现图表

    var chart = new CanvasJS.Chart({
      //Chart Options Goes Here
    });
    chart.render();
    

查看 CanvasJS Angular Gallery for more examples with code / samples that you can download & run locally. Here is a live example