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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With