Chart.js icon indicating copy to clipboard operation
Chart.js copied to clipboard

Framework-relate bug when importing adapters.

Open mstonepc opened this issue 1 year ago • 3 comments

Expected behavior

The adapter import should modify the correct chart.js instance.

Current behavior

When importing in a framework like ember, or react, because the package.json points requireJS to the ".cjs" file, and the import in those frameworks happens in node during build time, the adapter does not import the same chart instance, and therefore the adapter does not work.

Reproducible sample

https://github.com/chartjs/Chart.js/discussions/11376

Possible Solution

Perhaps both chart.js and chart.cjs in dist can target the same chart instance? I haven't dug too deep on how this is all setup right now. Does require really need the .cjs version?

chart.js version

v4

mstonepc avatar Mar 10 '24 15:03 mstonepc

This is likely because the Chart instance is just a global variable and there are two copies when two separate imports exist

etimberg avatar Mar 11 '24 12:03 etimberg

Am trying to use a chartjs plugin (chartjs-financial) and the same code that works perfectly in a simple non-framework app gives an error that it can't find the required controller (candlestick in this case) when using Ember. So, perhaps this is caused by the same error - is there a workaround right now?

eg271 avatar May 08 '24 01:05 eg271

This is likely because the Chart instance is just a global variable and there are two copies when two separate imports exist

Just a note for people with webpack, a workaround is via the webpack aliases config, something like what the OP' linked to: https://github.com/chartjs/Chart.js/discussions/11376

I also had to add this alias for the datalabels plugin:

  // ... 
  "chart.js/helpers": path.resolve(
    PATHS.root,
    "node_modules",
    "chart.js",
    "helpers",
  ), // ...

I suspect this issue stems from Chart.js supporting both CJS and ESM (i.e. { ..., "main": "chart.cjs", ... } .

I further suspect this link contains guidelines which may help guide Chart.js maintainers towards a resolution for those of us with this issue in the future (though I am not familiar with the project's requirements): https://redfin.engineering/node-modules-at-war-why-commonjs-and-es-modules-cant-get-along-9617135eeca1

(thanks @dfabulich )

Specifically:

  - Consider shipping only ESM
  - If you’re not shipping only ESM, ship CJS only
  - Test that your CJS works in ESM
  - If needed, add a thin ESM wrapper for your CJS named exports
  - Add an exports map to your package.json

Just my two cents. Big thanks to the maintainers here.

simian-loco avatar Jan 08 '25 12:01 simian-loco