chartjs-plugin-datalabels: Import error: "Module 'chartjs-plugin-datalabels/types/index' has no default export."

Trying out Chart.js, and have been told I need to use the chartjs-plugin-datalabels to be able to write the percentage text on the piew pieces.

I installed and imported the chartjs-plugin-datalabels as per the documentation into my Angular 7 project (actually Ionic 4, which uses Angular 7), but vscode reports the following error on the import…

Module '"../../../../node_modules/chartjs-plugin-datalabels/types"' has no exported member 'ChartDataLabels'.ts(2

I have the following versions "chart.js": "^2.8.0", "chartjs-plugin-datalabels": "^0.6.0",

If I go to the node_modules\chartjs-plugin-datalabels\types\index.d.ts file, I also see a similar error here for the line

declare module 'chart.js

Invalid module name in augmentation. Module 'chart.js' resolves to an untyped module at 'd:/dev/ionic/chartjstest/node_modules/chart.js/dist/Chart.js', which cannot be augmented.ts

If I proceed, and try to run, I then get the compile error

[ng] ERROR in node_modules/chartjs-plugin-datalabels/types/index.d.ts(5,16): error TS2665: Invalid module name in augmentation. Module 'chart.js' resolves to an untyped module at 'D:/dev/ionic/chartjstest/node_modules/chart.js/dist/Chart.js', which cannot be augmented. [ng] src/app/home/pie-graph/pie-graph.component.ts(3,10): error TS2305: Module '"D:/dev/ionic/chartjstest/node_modules/chartjs-plugin-datalabels/types/index"' has no exported member 'ChartDataLabels'.

About this issue

  • Original URL
  • State: closed
  • Created 5 years ago
  • Reactions: 1
  • Comments: 29 (7 by maintainers)

Most upvoted comments

@simonbrunel the correct way to import the library and get a reference to the output in Typescript is import * as ChartDataLabels from 'chartjs-plugin-datalabels'; (based on how the library is currently being exported)

You can fix this issue with installing the types for Chart.js via npm install @types/chart.js

@simonbrunel - ok thanks for that!

I tried the import 'chartjs-plugin-datalabels'; and removed the plugin stuff…

constructor() {
    //this.chartLabels = ChartDataLabels;
    // Chart.plugins.unregister(ChartDataLabels);
   }

 this.chart = new Chart(this.chartRef.nativeElement, { 
      //plugins: [ChartDataLabels],
      type: 'pie',
      data: this.data,
      options: options
    });
....

and now at least my formatter() is now called.

I now have

 let options : ChartOptions = {
      responsive: true,
      maintainAspectRatio: false,
      legend: {
        position: 'bottom',
        labels: {
          boxWidth: 20
        }
      },
      tooltips: {
        enabled: false
      },
      plugins: {
        datalabels: {
          formatter: (value, ctx) => {            
            let dataArr = ctx.chart.data.datasets[0].data;
            let total = sum(dataArr);     // sum from lodash        
            let percentage = (value * 100 / total).toFixed(2) + "%";
            return percentage;
          },
          color: 'black',
        }
      }
    };
    this.chart = new Chart(this.chartRef.nativeElement, {       
      type: 'pie',
      data: this.data,
      options: options
    });
  }

So I can now get my percentage labels!

image

I am sure I had tried the import 'chartjs-plugin-datalabels'; but I never had the formatter() called, but certainly seems to work now

npm i chartjs-plugin-datalabels

@Cimmeron you need to install @types/chart.js as suggested in other comments.

I think that’s because the TS declaration doesn’t export the plugin, so import ChartDataLabels from 'chartjs-plugin-datalabels'; doesn’t work with TS. I will need to investigate what’s the best way to fix it but in the meantime, you can import 'chartjs-plugin-datalabels'; (the old way), meaning that you will not be able to register the plugin per chart (neither unregister it globally).

@simonbrunel - yes for sure, I’ll include all my component code here. This is just a test app for my to try out chart.js, so is a little adhoc and untidy with me trying stuff out. But all has worked so far except for using this plugin

I created a new Ionic 4 blank application, and have installed the following…

dependencies:

"chart.js": "^2.8.0",
"chartjs-plugin-datalabels": "^0.6.0",

devDependencies

"@types/chart.js": "^2.7.50",

And the component code…

import { Component, OnInit, ViewChild } from '@angular/core';
import { Chart, ChartOptions } from 'chart.js';
import { ChartDataLabels } from 'chartjs-plugin-datalabels';
//import 'chartjs-plugin-datalabels';

@Component({
  selector: 'app-pie-graph',
  templateUrl: './pie-graph.component.html',
  styleUrls: ['./pie-graph.component.scss'],
})
export class PieGraphComponent implements OnInit {
  @ViewChild('mygraph') private chartRef;
  chart: Chart;

  chartLabels: any;

  data: any;
  constructor() {
    //this.chartLabels = ChartDataLabels;
    Chart.plugins.unregister(ChartDataLabels);
   }

  public updateClick(evt) : void {
    try {
      let activePoints = this.chart.getElementsAtEvent(evt);
      let i = 0;  

      this.data.datasets[0].data[0] = 44;
      this.chart.update();
    } catch (error) {
      alert(error);
    }
    
  }

  public ngOnInit() : void {
    this.data = {
      datasets: [{
        data: [10, 20, 30, 50],
        backgroundColor: [
          'green',
          'rgba(54, 162, 235, 0.2)',
          'rgba(255, 206, 86, 0.2)',
          'rgba(75, 192, 192, 0.2)',
          'rgba(153, 102, 255, 0.2)',
          'rgba(255, 159, 64, 0.2)'
        ],
      }],

      // These labels appear in the legend and in the tooltips when hovering different arcs
      labels: [
        'Red',
        'Yellow',
        'Blue',
        'another'
      ]
    };

    let options : ChartOptions = {
      responsive: true,
      maintainAspectRatio: false,
      legend: {
        position: 'bottom',
        labels: {
          boxWidth: 20
        }
      },
      tooltips: {
        enabled: false
      },
      plugins: {
        datalabels: {
          formatter: (value, ctx) => {
            return 'hello';
            let sum = 0;
            let dataArr = ctx.chart.data.datasets[0].data;
            // dataArr.map()
            // dataArr.map((data, i, array) => {
            //   sum += data;
            // });
            let percentage = (value * 100 / sum).toFixed(2) + "%";
            return percentage;


          },
          color: 'black',
        }
      }
    };
    this.chart = new Chart(this.chartRef.nativeElement, { 
      plugins: [ChartDataLabels],
      type: 'pie',
      data: this.data,
      options: options
    });
  }
}

I can share the whole project if that is of any help

Hello All,

How to build a doughnut chart only using chart.js and typescript?

I have the following versions “chart.js”: “^3.3.2” and “@types/chart.js”: “^2.9.32”.

I am able to display the chart. But I want to achieve the below requirements as well.

  1. Display text inside the doughtnut chart
  2. Display DataLabels in each segment
  3. Need to change the color of hidden legend instead of Strike-Through

I am getting the dependency error when I try to install npm chartjs-plugin-datalabels.

npm ERR! node_modules/chart.js npm ERR! chart.js@“^3.3.2” from the root project npm ERR! npm ERR! Could not resolve dependency: npm ERR! peer chart.js@“>= 2.7.0 < 3” from chartjs-plugin-datalabels@1.0.0 npm ERR! node_modules/chartjs-plugin-datalabels

Any suggestion please to resolve this issue?

Thanks!

This is fixed by 92771df1588e80df1d5a70cbd8d53557222c3205 and will be released in v0.7.0. The proper way to include this plugin in TS will be:

import ChartDataLabels from 'chartjs-plugin-datalabels';

// or

import { default as ChartDataLabels  } from 'chartjs-plugin-datalabels';

@pjc2007 How do you import this plugin? can you share the code of your project so it will be easier to debug?

Those last two errors listed look like problems in your usage.

The false error looks like you are setting a property wrong. Double check your usage of the library there as the types aren’t matching up.

For the second one, you should import the library like import * as ChartDataLabels from 'chartjs-plugin-datalabels';. The library isn’t exporting things like you are probably used to in Typescript.