laravelnpmlaravel-livewirealpine.jslaravel-sail

Default AlpineJS installation in sail livewire project


My question comes from simple curiosity, as I'd like to have control over the dependency versions of my project. Recently I started to work on a laravel/livewire project installed with Sail. I noticed that there are some ui features, which would be handled much better by a lightweight js framework, so I went with AlpineJS. I installed it with npm, and everything worked fine, until at some point I started to get some weird uncaught exception errors. After looking around, in many places the solution was to make sure that AlpineJS is not loaded multiple times. So I removed my Alpine registration from the app.js, and for my surprise everything still worked as expected with no error anymore. I tried to find where that AlpineJS installation comes from, but unable to find it. No script tags in the project and no imports using the cdn url. Wondering if the container has it somehow globally installed (it should still be initialized somewhere though).

Is any livewire/alpinejs guru around here who can tell me where to look, or give me an insight how it works?

It's not the end of the world, but as I said, I'd like to have a control over what alpinejs version is used after deployment. And also good to know how certain things work in the framework. Thanks.


Solution

  • Livewire v3 comes with Alpinejs installed by default. However, you can manually load it.

    To achieve this, you must add the @livewireScriptConfig directive to your layout file (resources/views/components/layouts/app.blade.php):

    <html>
    <head>
        <!-- ... -->
        @livewireStyles
        @vite(['resources/js/app.js'])
    </head>
    <body>
        {{ $slot }}
     
        @livewireScriptConfig 
    </body>
    </html>
    

    When Livewire detects the @livewireScriptConfig directive, it will refrain from injecting the Livewire and Alpine scripts. If you are using the @livewireScripts directive to manually load Livewire, be sure to remove it. Make sure to add the @livewireStyles directive if it is not already present.

    The final step is importing Alpine and Livewire in your app.js file, allowing you to register any custom resources, and ultimately starting Livewire and Alpine. You can also install your preferred Alpinejs version via npm and import it in the app.js as shown:

    import { Livewire, Alpine } from '../../vendor/livewire/livewire/dist/livewire.esm';
    import Clipboard from '@ryangjchandler/alpine-clipboard'
     
    Alpine.plugin(Clipboard)
     
    Livewire.start()
    

    This is only compatible with Vite and not Laravel mix.

    Livewire Docs