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

tyteck's avatar

Alpine Expression Error: Chart is not defined

Hello to all I'm bumping into the error below and even though I think I know why but I don't have enough javascipt skills to fix it.

my vite.config.js configuration

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

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

app.js

import Alpine from 'alpinejs'
import Chart from 'chart.js/auto'
import '../css/app.css'
window.Alpine = Alpine
Alpine.start()

the head

<head>
@vite(['resources/js/app.js'])
</head>

the failing part (blade)

<div>
    <div x-data="{
        init() {
            const ctx = document.getElementById('temperatures');
            const config = {
              ...
            };
    
            const myChart = new Chart(ctx, config);
        }
    }" class="mt-1 relative">
   ...
   <canvas id="temperatures"></canvas>
</div>

if I do a console.log(Chart) in app.js I see that Chart exists. but I fail to send it to Alpine. If you have any solution I'm interested. Have a nice day

0 likes
4 replies
LaryAI's avatar
Level 58

The issue might be that Alpine is trying to access the Chart object before it has been fully loaded. One solution could be to use the defer attribute on the script tag that loads the Alpine library. This will ensure that Alpine is loaded after all other scripts have been loaded.

Here's an example of how to modify the script tag in the head section:

<head>
    @vite(['resources/js/app.js'])
    <script defer src="{{ mix('js/alpine.js') }}"></script>
</head>

If this doesn't solve the issue, another solution could be to use the x-init directive instead of defining a method in the x-data object. This will ensure that the Chart object is fully loaded before it is accessed by Alpine.

Here's an example of how to modify the div in the blade file:

<div x-data="{ }" x-init="init()" class="mt-1 relative">
    ...
    <canvas id="temperatures"></canvas>
</div>
tyteck's avatar

thanks for your help "Larry" but this is not working. init() function is called (I put one console.log() to check). the problem is that Chart Class seems not being passed. const myChart = new Chart(ctx, config); is failing Chart Class/Lib is not known inside init() function.

kiwi0134's avatar
kiwi0134
Best Answer
Level 8

You might want to try to bind it to the window before calling Alpine, like:

import Alpine from 'alpinejs'
import Chart from 'chart.js/auto'
window.Alpine = Alpine
window.Chart = Chart
Alpine.start()
1 like
tyteck's avatar

Arf I feel so dumb in javascript. Many thanks for your help šŸ™

1 like

Please or to participate in this conversation.