Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
pjc2007 opened this issue Apr 11, 2019 · 29 comments

Comments

@pjc2007
Copy link

pjc2007 commented Apr 11, 2019

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'.

@danielwstrimpel
Copy link

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

@pjc2007
Copy link
Author

pjc2007 commented Apr 11, 2019

@danielwstrimpel I installed this, but now get further errors as well as the original.

So I still have the error at the import...
"@types/chart.js": "^2.7.50",

But I still get the import error...

image.

And the following compile error..

[ng] ERROR in src/app/home/line-graph/line-graph.component.ts(55,17): error TS2559: Type 'false' has no properties in common with type 'ChartLegendOptions'.
[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'.
[ng]

@danielwstrimpel
Copy link

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.

@pjc2007
Copy link
Author

pjc2007 commented Apr 11, 2019

@danielwstrimpel - yes some of those errors are coming from another (test) component where I was trying the Chart as a line graph. Funny everything I set in there worked, and now it is telling me some of the options are not valid...

I wonder if the typedef is up to date with the library?

At any rate, I commented out these, so can just look at the error we are concerned with here.

So now, I still have the import error, and now the only compile error is


[ng] ERROR in 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'.
[ng] 

Yes, I certainly want to know how to import this into a TypeScript project (if that is different for some reason)

@simonbrunel
Copy link
Member

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

@simonbrunel simonbrunel changed the title chartjs-plugin-datalabels import via npm has error Invalid module name in augmentation. Module 'chart.js' resolves to an untyped module Import error: "Invalid module name in augmentation" Apr 11, 2019
@pjc2007
Copy link
Author

pjc2007 commented Apr 11, 2019

@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

@simonbrunel
Copy link
Member

@pjc2007 I installed and imported the chartjs-plugin-datalabels as per the documentation...

Per the documentation:

import ChartDataLabels from 'chartjs-plugin-datalabels';

@pjc2007
Copy link
Author

pjc2007 commented Apr 11, 2019

@simonbrunel - oh ok, yes I did add the braces when I I got the error it without them.

I changed back so now I have...

image

IF we required, whole repo is at https://github.com/pjc2007/testChartjs

@simonbrunel
Copy link
Member

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).

@pjc2007
Copy link
Author

pjc2007 commented Apr 11, 2019

@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

@simonbrunel simonbrunel changed the title Import error: "Invalid module name in augmentation" Import error: "Module 'chartjs-plugin-datalabels/types/index' has no default export." Apr 11, 2019
@simonbrunel simonbrunel added bug and removed support labels Apr 11, 2019
@danielwstrimpel
Copy link

danielwstrimpel commented Apr 11, 2019

@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)

@pjc2007
Copy link
Author

pjc2007 commented Apr 11, 2019

@danielwstrimpel - I tried this and seems to work 100%! Thanks for that.

Wonder if that could be put in the doco for other Angular / TypeScript users (there are a lot of people in this category that use this library)?

So, I can now type everything which helps a lot with getting setup correct.

So, the full code is now as follows.

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

@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;
  data: ChartData;
  constructor() {
    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) => {
            let dataArr = ctx.chart.data.datasets[0].data;
            let total = sum(dataArr);
            let percentage = (value * 100 / total).toFixed(2) + "%";
            return percentage;
          },
          color: 'black',
        }
      }
    };
    this.chart = new Chart(this.chartRef.nativeElement, { 
      plugins: [ChartDataLabels],
      type: 'pie',
      data: this.data,
      options: options
    });
  }
}

@simonbrunel
Copy link
Member

@pjc2007 @danielwstrimpel I'm not sure why * as ... works in TS but it's not the way we want to promote for importing this plugin. It's better to fix the TS declaration instead of documenting different methods for ES6 or TS, something like this in types/index.d.ts:

declare var plugin: object;

export default plugin;

So users can import using:

import ChartDataLabels from 'chartjs-plugin-datalabels';

Note that this change would break import * as ChartDataLabels ...

@pjc2007
Copy link
Author

pjc2007 commented Apr 11, 2019

@simonbrunel Imports are the one thing that always "get me" in TypeScript , and I can spend hours trying to work it out when they are not "standard", so yes I agree with you.

The imports syntax from the chart.js is how most seem to be, i.e.

import { Chart, ChartOptions, ChartData } from 'chart.js';

So you can import individual classes (listing each inside of the { })

Also in some cases, from what I understand, this can also have the potential to help with "tree shaking" i.e. not having to import everything.

@lenichols
Copy link

+1

@simonbrunel simonbrunel added this to the Version 0.7 milestone May 5, 2019
@simonbrunel
Copy link
Member

This is fixed by 92771df 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';

@sandyeveliz
Copy link

Adding this as @pjc2007 says work out for me in Dev Builds

devDependencies

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

@geyuqiu
Copy link

geyuqiu commented Jun 12, 2019

Temporarily I resolved the error by changing the type of chart to any instead of Chart.

@DnyaneshBaravkar
Copy link

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

Thanks its working...

@simonbrunel
Copy link
Member

Released in version 0.7.0.

@Cimmeron
Copy link

I just installed this and using

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

I get the error

ERROR in node_modules/chartjs-plugin-datalabels/types/index.d.ts(3,16): error TS2665: Invalid module name in augmentation. Module 'chart.js' resolves to an untyped module at 'c:/SVN_repos/devel opment/src/dms_client/trunk/node_modules/chart.js/dist/Chart.js', which cannot be augmented.

The only import that works is import 'chartjs-plugin-datalabels';

@simonbrunel
Copy link
Member

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

@quyennguyenvan
Copy link

quyennguyenvan commented Dec 19, 2019

i dont know, until now, i still can't using this plugin when import

error response
ERROR in src/app/dashboard/inventory/inventory.component.ts(14,45): error TS2307: Cannot find module 'chartjs-plugin-datalabels'.

@dssagar93
Copy link

dssagar93 commented Mar 20, 2020

When I had installed @types/chart.js, it gave me another error for

font: {
            weight: '500'
}

inside
datalabels

I had to comment this one out and also I commented
weight?: 'normal' | 'bold' | 'bolder' | 'lighter' | number in node_modules\chartjs-plugin-datalabels\types\options.d.ts
and the error was gone. A temporary fix maybe.

@HamzaNb
Copy link

HamzaNb commented Apr 23, 2020

npm i chartjs-plugin-datalabels

@hunterwick
Copy link

Here is a solution that will always work:

You will need @types/chartjs
add any behind each error that the compiler will throw

Importing
import * as ChartDataLabels from 'chartjs-plugin-datalabels'; Chart.plugins.unregister(ChartDataLabels as any);

Some example inside the code
const placeHolder = document.getElementById('chartPlaceHolder') as HTMLCanvasElement;

this.subChart = new Chart(placeHolder as HTMLCanvasElement, {
type: 'doughnut',
plugins: [ChartDataLabels as any],
data: chartData.data,
options: chartData.options as any
});

You can put as any if you dont know the required type
Else put the object type directly

@NandhiniMuthuramalingam

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!

@Messa1
Copy link

Messa1 commented Aug 28, 2023

I also got some error try to use the lib with TS.
Does anyone have a hint?

The types of 'datalabels.anchor' are incompatible between these types.
          Type 'string' is not assignable to type '"end" | "center" | "start" | Anchor[] | ((context: Context) => Anchor)'.
import React from 'react';
import { Doughnut } from 'react-chartjs-2';
import 'chart.js/auto';
import { Chart } from 'chart.js';
import ChartDataLabels from 'chartjs-plugin-datalabels';
.....

const DonutChart: React.FC<DonutChartProps> = ({ data }) => {
  const chartData = {
    labels: data.map(item => item.label),
    datasets: [
      {
        data: data.map(item => item.value),
        backgroundColor: ['#003333', '#006969', '#004D4D'],
        hoverBackgroundColor: ['#003333', '#006969', '#004D4D'],
        borderWidth: 0,
        datalabels: {
          anchor: 'end',
          labels: {
            value: {
              backgroundColor: 'white',
              
.....

@Gander-Malkiat
Copy link

Just copy chart
chartjs-plugin-datalabels.js
and reference that directly

import 'assets/js/chartjs-plugin-datalabels.js';

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests