Asset Building & Vite

Asset Building & Vite

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:

Bash
node -v
npm -v

Download 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:

PHP
@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:

Bash
npm install tailwindcss @tailwindcss/vite

Add Tailwind directives to your CSS. Like so:

PHP
@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:

Bash
npm run build

to generate optimized, minified assets for deployment.

Tags: