Auto-Refresh Livewire Components While Keeping States With Vite
#javascript #laravelVite 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.
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.
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.