I try to use CanvasJS into an Angular 11 project, but I have an error with the import:
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",
My import in my component looks like this (no error):
import * as CanvasJS from 'canvasjs';
I initialize the chart (code from sample) on 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();
}
What I'm missing?
You seem to be using outdated / unofficial version of CanvasJS. Follow the below steps to add CanvasJS charts in your Angular application.
Download the official version from CanvasJS Download Page / commercial version from My Account Page.
Save canvasjs.min.js in app folder
Import the library
import * as CanvasJS from './canvasjs.min';
Create & render chart
var chart = new CanvasJS.Chart({
//Chart Options Goes Here
});
chart.render();
Check out CanvasJS Angular Gallery for more examples with code / samples that you can download & run locally. Here is a live example.