Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

vincent15000's avatar

Add chart.js to Laravel with npm

Hello,

I have installed chart.js with npm and I try to use it in a view.

I have added this in the app.js file.

import Chart from 'chart.js/auto';

window.Chart = Chart;

And then I have added this a the view.

<section>
	<canvas id="myChart"></canvas>
</section>
...
<script>
  const ctx = document.getElementById('myChart');

  new Chart(ctx, {
    type: 'bar',
    data: {
      labels: ['Red', 'Blue', 'Yellow', 'Green', 'Purple', 'Orange'],
      datasets: [{
        label: '# of Votes',
        data: [12, 19, 3, 5, 2, 3],
        borderWidth: 1
      }]
    },
    options: {
      scales: {
        y: {
          beginAtZero: true
        }
      }
    }
  });
</script>

I get this error in the console.

Uncaught ReferenceError: Chart is not defined

I have try with window.Chart but I get the same error with window.Chart not defined.

Any idea ?

Thanks ;).

V

0 likes
10 replies
Sinnbeck's avatar

Make sure you include the script from vite before you own script

1 like
vincent15000's avatar

@Sinnbeck My own script is directly inside the view. I think (but not sure) that the script from vite is loaded before no ?

vite.config.js

import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';

export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/css/app.css', 'resources/js/app.js'],
            refresh: true,
        }),
    ],
});
Sinnbeck's avatar

@vincent15000 check your dom. And try typing Chart in the browser console to see if it is even loaded

1 like
vincent15000's avatar

@Sinnbeck Yes it's loaded, I see its class in the console.

class {
  static register(...items) {
    registry.add(...items);
    invalidatePlugins();
  }
  static unregister(...items) {
    registry.remove(...items);
    invalidatePlugins();
  }
  constructor(item…
vincent15000's avatar

@Sinnbeck Ok it works with telling my script a a module.

Can you explain me why it makes a difference ?

Please or to participate in this conversation.