Interested how Laravel works under the hood? → Check my Laravel Core Adventures Course

Auto-Refresh Livewire Components While Keeping States With Vite

#javascript #laravel

Vite is the new front-end tooling for Laravel. Let's see how we can make it work better together with Laravel Livewire.

Vite is the Next Generation Frontend Tooling, which is Laravel's default from now on. I already wrote an article on how to move a Laravel Webpack site to Vite.

Today, let's check out how we can improve working with Livewire and Vite together, by using the Vite Livewire Plugin by Fabio Ivona.

The Need

When working with Laravel Livewire, our components often have different states, depending on the current data.

Every time we change the component's blade file and refresh, all states are gone, and the component is set to its default.

This is where the Vite Livewire Plugin can help us. It auto-refreshes Livewire components and keeps its current state.

Screenshot of the website Larastreamers of the submit modal which is a livewire component.
Image: This submission form is a Livewire component from the Larastreamers website.

Setup

Install the package.

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

Then add the new Vite plugin to your vite.config.js file.

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

import livewire from '@defstudio/vite-livewire-plugin'; // Here we import it

export default defineConfig({
    plugins: [
        laravel([
            'resources/css/app.css',
            'resources/js/app.js',
        ]),
        
       livewire({  // Here we add it to the plugins
           refresh: ['resources/css/app.css'],
       }),
    ],
});

And last, add the reload manager to your main JavaScript file.

//..

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

No we can start Vite through npm run dev, and you should see a console message that the Vite Livewire plugin is successfully enabled. This means you are ready to go.

Screenshot of the website Larastreamers of the submit modal which is a livewire component.
Note: Be aware that if you already have Vite configured to auto-refresh blade files, that this will conflict with this plugin.

Usage

Every time you now change a Livewire component's blade file, or the component class, it will be automatically refreshed while keeping the state. Pretty cool, right?

This is super useful, especially for more extensive components like huge forms with lots of input fields. When you test them now, you don't have to refill all data again.

For more details, please check the official plugin documentation. Have fun, and thanks to Fabio Ivona.

Do you enjoy my posts?

Sign up for my newsletter to receive updates on my latest content.

You will receive monthly updates on my latest articles and products. I do care about the protection of your data. Read my Privacy Policy.