Here’s a short explanation about asset bundling and Vite in Laravel, which optimize and manage your application’s frontend assets like CSS, JavaScript, and images for production.
What is Asset Bundling?
Asset bundling combines and optimizes your assets to reduce load times and improve performance. This includes minification, compression, and efficient loading.
Using Vite in Laravel
Laravel integrates with Vite out of the box. Your package.json includes dependencies like vite and @vitejs/plugin-vue.
Installing Node.js and NPM
Ensure you have Node.js and npm installed. Check with:
node -v
npm -vDownload from nodejs.org if needed.
Vite Configuration
The vite.config.js file specifies entry points for your CSS and JavaScript, typically located in the resources directory.
Running Vite
Use npm scripts to run Vite:
npm run dev— starts the development server with hot module replacement (HMR).npm run build— compiles and optimizes assets for production.
Including Assets in Blade
Use Laravel’s @vite directive in your Blade templates to include your compiled assets:
@vite(['resources/css/app.css', 'resources/js/app.js'])Hot Reloading
While running npm run dev, changes to your CSS or JS files automatically refresh the browser, improving development speed.
Tailwind CSS Integration
Instead of using the CDN, install Tailwind CSS via npm for production:
npm install tailwindcss @tailwindcss/viteAdd Tailwind directives to your CSS. Like so:
@import 'tailwindcss';
@source '../../vendor/laravel/framework/src/Illuminate/Pagination/resources/views/*.blade.php';
@source '../../storage/framework/views/*.php';
@source '../**/*.blade.php';
@source '../**/*.js';
@source "../views";
@theme {
--font-sans: 'Instrument Sans', ui-sans-serif, system-ui, sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji',
'Segoe UI Symbol', 'Noto Color Emoji';
--color-laracasts: rgb(50 138 241);
}Building for Production
Run:
npm run buildto generate optimized, minified assets for deployment.
