Uncaught TypeError: Chart is not a constructor when using Chart.js
Asked Answered
B

5

7

I'm working on my first Cordova projects and am trying to use Chart.js. The documentation states that Chart.js should be included like this:

<script src="Chart.js"></script>
<script>
    var myChart = new Chart({...})
</script>

I installed the library using bower and it is now present under www/lib/chart.js. Chrome gives me Failed to load resource: the server responded with a status of 404 when I'm loading Chart.js or lib/chart.js.

When I load lib/chart.js/src/chart.js I get a different error saying Uncaught TypeError: Chart is not a constructor in this line:

  var ctx = document.getElementById("myChart");
  var myChart = new Chart(ctx, { //...

This is what's in the file chart.js:

var Chart = require('./core/core.js')();

require('./core/core.helpers')(Chart);
// ...

window.Chart = module.exports = Chart;

Is this the right chart.js file?

Bicycle answered 31/1, 2017 at 20:38 Comment(0)
H
5

I think that chart.js you're using has an error
try this one:

<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.4.0/Chart.min.js"></script>

Hydroxylamine answered 31/1, 2017 at 20:46 Comment(2)
That works fine for me, thanks! Any idea on how to use the local jar?Bicycle
<script src="cdnjs.cloudflare.com/ajax/libs/Chart.js/3.9.1/…> also works and is a newer versionGolly
H
3

On Laravel mix use:

window.Chart = require('chart.js/auto').default;
Handtohand answered 17/2, 2022 at 0:4 Comment(0)
V
2

Do this and it should work import Chart from 'chart.js/auto';

https://www.chartjs.org/docs/latest/getting-started/integration.html

Vadavaden answered 16/2, 2022 at 14:4 Comment(0)
M
2

If you are using Chart.js v3 or higher:

import Chart from 'chart.js/auto';

If you are using Chart.js v2:

import Chart from "chart.js";
Mur answered 26/8, 2023 at 18:1 Comment(0)
H
0

Still ran into this with chartjs 4.4.3 and webpack. In the end, using the following worked:

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

instead of the documented:

import Chart from 'chart.js/auto'
Hayott answered 13/7 at 17:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.