chartjs / chartjs-plugin-datalabels

Chart.js plugin to display labels on data elements
https://chartjs-plugin-datalabels.netlify.app
MIT License
863 stars 459 forks source link

datalabes plugin doesn't work with ES module #392

Open hounaida3060 opened 11 months ago

hounaida3060 commented 11 months ago

I use chartjs in my project and I need to display data on Doughnut. So, I install the plugin of datalabels

`import { Chart , registerables } from 'chart.js'; import { Doughnut } from 'react-chartjs-2'; import ChartDataLabels from 'chartjs-plugin-datalabels';

Chart.register(...registerables, ChartDataLabels)`

But it doesn't work by adding the plugin in register, Igave the following error

Uncaught Error: Dynamic require of "chart.js/helpers" is not supported at chartjs-plugin-datalabels.js:7:9 at chartjs-plugin-datalabels.js:8:89 at node_modules/chartjs-plugin-datalabels/dist/chartjs-plugin-datalabels.js (chartjs-plugin-datalabels.js:11:1) at __require2 (chartjs-plugin-datalabels.js:10:50) at chartjs-plugin-datalabels.js:1356:3 (anonyme) @ chartjs-plugin-datalabels.js:7 (anonyme) @ chartjs-plugin-datalabels.js:8 node_modules/chartjs-plugin-datalabels/dist/chartjs-plugin-datalabels.js @ chartjs-plugin-datalabels.js:11 __require2 @ chartjs-plugin-datalabels.js:10 (anonyme) @ chartjs-plugin-datalabels.js:1356

Any help please

Whobeu commented 6 months ago

Unfortunately, chartjs-plugin-datalabels does not play nice in a dual CommonJS/ESM environment using Node.js. I was having a bear of a time trying to get labels to work properly with ESM and Node.js. I could get the labels to display but could not get them in their correct location due to failure of "instanceof" in one of the modules. That was due to the plugin loading in CommonJS mode rather than ESM mode. I did try creating a simple package.json in the "dist" directory with

{
  "type": "module"
}

which did work but broke CommonJS support. Ultimately, after some hacking in the chartjs-plugin-datalabels directory of node_modules, I came up with a workable solution though it will get wiped if I ever do an "npm update".

First I add the following to the package.json file:

  "exports":{
    "import":"./dist/chartjs-plugin-datalabels.esm.mjs",
    "require":"./dist/chartjs-plugin-datalabels.js"
  },

Then I copy chartjs-plugin-datalabel.esm.js to chartjs-plugin-datalabel.esm.mjs. Once that is done, both CommonJS and ESM routines work fine. The crazy thing is that within the package.json file there is an entry that says

"module": "dist/chartjs-plugin-datalabels.esm.js",

IMHO, this would solve the problem of CommonJS/ESM interoperability with Node.js EXCEPT, Node.js ignores the "module" property of package.json [rolls-eyes]. So the best solution at this time is to add the "exports" property and make a .mjs copy of the ESM module.

igordata commented 1 week ago

added "type": "module" but it would be great if someone could explain why no one else if facing this issue.