Lifetime access is $100 off. Available for a limited time.Join here →

Prevent Livewire Refreshes and State Loss When Hot Reloading with Vite

February 22nd, 2024

If you're here, you're likely suffering from unexpected state loss in your Livewire components when using Vite.

Here's the picture — you fire up npm run dev and start building your Livewire components. But, as soon as you change something and head back to your browser to interact with your Livewire components, your browser seems to refresh itself, and/or you lose all current state in your Livewire components.

Pretty annoying.

The vite-livewire-plugin solves this issue by configuring Vite for use with Livewire. Here's how to add it.

First up, install the plugin with npm.

npm install --save-dev @defstudio/vite-livewire-plugin

Next, add the plugin to your vite.config.js file and point it to your CSS files so they can get refreshed too.

import livewire from '@defstudio/vite-livewire-plugin'

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

        livewire({
            refresh: ['resources/css/app.css'],
        }),
    ],
})

You'll also want to explicity set refresh to false with the Laravel Vite plugin to avoid conflicts (see above).

Finally, add the hot reload manager to your app.js file.

import { livewire_hot_reload } from 'virtual:livewire-hot-reload'

livewire_hot_reload()

You should no longer have any issues with unexpected refreshing or state loss when working with Livewire and Vite.

I'd highly recommend heading to the official vite-livewire-plugin site to see more options, and keep up to date with any changes to the plugin.

A massive thanks to Fabio Ivona from def:studio for authoring this plugin and saving us all from unexpected state changes when using Livewire under Vite!

Thanks for reading! If you found this article helpful, you might enjoy our practical screencasts too.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first to leave a comment.

Tagged under