Skip to content

Đóng gói tài nguyên (Asset Bundling - Vite)

Giới thiệu (Introduction)

Vite là công cụ build frontend hiện đại cung cấp development environment cực nhanh và đóng gói code cho production. Laravel tích hợp chặt chẽ với Vite qua plugin chính thức và Blade directive để tải assets.

Cài đặt và Thiết lập (Installation & Setup)

Cài đặt Node

Cần Node.js (16+) và NPM:

bash
node -v
npm -v

Cài đặt Vite và Laravel Plugin

Laravel mới đã bao gồm vite.config.js và plugin. Nếu cần cài thủ công:

bash
npm install --save-dev vite laravel-vite-plugin

Cấu hình Vite

File vite.config.js ở gốc project:

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

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

Tải Scripts và Styles

Dùng Blade directive @vite trong layout:

blade
<!DOCTYPE html>
<head>
    {{-- ... --}}
    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>

Chạy Vite (Running Vite)

bash
# Development server (HMR)
npm run dev

# Build cho production
npm run build

Làm việc với JavaScript

Aliases

Thêm aliases trong vite.config.js:

js
export default defineConfig({
    // ...
    resolve: {
        alias: {
            '@': '/resources/js',
        },
    },
});

Vue

bash
npm install --save-dev @vitejs/plugin-vue
js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import vue from '@vitejs/plugin-vue';

export default defineConfig({
    plugins: [
        laravel({
            input: ['resources/js/app.js'],
            refresh: true,
        }),
        vue({
            template: {
                transformAssetUrls: {
                    base: null,
                    includeAbsolute: false,
                },
            },
        }),
    ],
});

React

bash
npm install --save-dev @vitejs/plugin-react
js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
import react from '@vitejs/plugin-react';

export default defineConfig({
    plugins: [
        laravel({
            input: 'resources/js/app.jsx',
            refresh: true,
        }),
        react(),
    ],
});

Thêm directive @viteReactRefresh trước @vite:

blade
@viteReactRefresh
@vite('resources/js/app.jsx')

Inertia

Laravel Vite plugin cung cấp hàm resolvePageComponent cho Inertia page components:

js
import { createInertiaApp } from '@inertiajs/vue3';
import { resolvePageComponent } from 'laravel-vite-plugin/inertia-helpers';

createInertiaApp({
    resolve: (name) => resolvePageComponent(
        `./Pages/${name}.vue`,
        import.meta.glob('./Pages/**/*.vue')
    ),
    // ...
});

Làm việc với Stylesheets

Import CSS trong vite.config.js hoặc trong JavaScript:

js
// resources/js/app.js
import '../css/app.css';

Vite hỗ trợ PostCSS, Sass, Less, Stylus. Xem Vite CSS docs.

Làm việc với Blade và Routes

Xử lý Static Assets

Tham chiếu assets được xử lý bởi Vite:

blade
<img src="{{ Vite::asset('resources/images/logo.png') }}">

Refresh khi lưu file

Plugin tự động refresh browser khi Blade files thay đổi (option refresh: true).

Asset Prefetching

Mặc định, Vite prefetches assets khi tải SPA pages, cải thiện UX. Tùy chỉnh stratègie:

php
// Trong AppServiceProvider boot()
Vite::prefetch(concurrency: 3);
Vite::useWaterfallPrefetching(concurrency: 10);
Vite::useAggressivePrefetching();

Custom Base URLs

Nếu Vite compiled assets deploy trên CDN:

env
ASSET_URL=https://cdn.example.com

Prefix URLs sẽ sử dụng ASSET_URL.

Environment Variables

Inject biến môi trường vào JavaScript bằng prefix VITE_ trong .env:

env
VITE_SENTRY_DSN_PUBLIC=http://example.com

Truy cập:

js
import.meta.env.VITE_SENTRY_DSN_PUBLIC

Tắt Vite trong Tests

php
use Illuminate\Foundation\Testing\Concerns\InteractsWithVite;

// Trong test
$this->withoutVite();

Server-Side Rendering (SSR)

Cấu hình SSR entry point trong vite.config.js:

js
laravel({
    input: 'resources/js/app.js',
    ssr: 'resources/js/ssr.js',
}),

Build and chạy SSR:

bash
npm run build
php artisan inertia:start-ssr