Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught ReferenceError: Alpine is not defined

Using Alpine with Laravel Vite is not working as expected. I'm getting the error: Uncaught ReferenceError: Alpine is not defined

My app.js file:

import Alpine from 'alpinejs';

Alpine.start();

window.Alpine = Alpine; // this should make Alpine globally accessible, right?

Including the app.js file in the head with: @vite('resources/js/app.js')

Then, when trying to use Alpine I placed the following script on the page:

<script type="text/javascript">
    document.addEventListener('alpine:init', () => {
        console.log('alpine loaded') // this works so the event listener is called
        console.log(Alpine) // Uncaught ReferenceError: Alpine is not defined
    });
</script>

When opening the developer console and typing Alpine the object does actually exist. Any ideas on why Alpine isn't available in the global scope?

like image 544
Vinze Avatar asked Feb 05 '26 00:02

Vinze


2 Answers

You should do it like that.

import Alpine from 'alpinejs';

window.Alpine = Alpine;

Alpine.start();

Then add @vite('resources/js/app.js') in the header of your blade file.

like image 117
Johny22 Avatar answered Feb 06 '26 12:02

Johny22


How you are ordering vite manifest and importing livewireStyles may be the issue. So alpine is loaded automatically incase you are using livewire 3 or anything above that. In your layout file first add the vite manifest @vite(['resources/js/app.js']) and in the app.js, you necessarily DO NOT need to have this...

// import Alpine from 'alpinejs';
// window.Alpine = Alpine;
// Alpine.start();

.... as it would lead to an error Alpine instance loaded twice. Not a big issue but it is good to have that in mind. After vite you can then put @livewireStyles and this should remove the console.log errors and import alpine globally.

like image 36
Indeche Ojukwu Avatar answered Feb 06 '26 13:02

Indeche Ojukwu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!