how to use require(chart.js) in codesandbox

130 Views Asked by At

I was trying to do this in a codesandbox:

const Chart = require("chart.js");
  plot() {
    this.chart = new Chart(this.chartRef.current, {
     ..
          }
        ]
      }
    });
  }

However, I get an error on require:

Cannot find name 'require'.

and that Chart is not a constructor

I also tried replacing it with

import Chart from chart.js

but that also doesnt work. How can I fix my codesandbox? Here's a link

https://codesandbox.io/s/opur8?file=/src/Graph.tsx:2009-2333

2

There are 2 best solutions below

0
On BEST ANSWER

To load and register everything, try:

import Chart from 'chart.js/auto';

...which is short for...

import { Chart, registerables } from 'chart.js';
Chart.register(...registerables);

...which in turn is short for importing and registering every part individually. See the documentation for more examples.

0
On

Chart class is exported as a named export.

Use: import {Chart} from 'chart.js'