Cách cài đặt Bootstrap 5 trong Laravel 9 với Vite

Bootstrap và Vite đều là hai cái tên nổi tiếng trong thế giới lập trình. Vậy cài Bootstrap 5 trong Laravel 9 với Vite như thế nào? Hãy cùng Quantrimang.com tìm hiểu nhé!

Bootstrap và Laravel

Bootstrap là gì?

Bootstrap là một framework phát triển web miễn phí, mã nguồn mở. Nó được thiết kế để làm quá trình lập trình web dễ chịu hơn với người mới, đặc biệt dành cho mobile bằng cách cung cấp một bộ sưu tập cú pháp cho các thiết kế mẫu.

Nói cách khác, Bootstrap giúp lập trình viên web xây dựng web nhanh hơn bởi họ không cần lo nghĩ tới các lệnh và chức năng cơ bản. Nó chứa HTML, CSS và các tập lệnh dựa trên JS cho các hàm, phần tử liên quan tới thiết kế web.

Điểm nổi bật của Bootstrap

  • Dễ bắt đầu.
  • Bao gồm cả file LESS và CSS.
  • Dễ dàng tùy chỉnh.
  • Class tiện ích đáp ứng.
  • Nhiều thành phần tạo kiểu cho Bootstrap.
  • Menu thành phần thả xuống.
  • Nhiều mẫu đa dạng.

Vite là gì?

Vite là một công cụ xây dựng, được thiết kế nhằm mục đích cung cấp trải nghiệm phát triển web nhanh và thoải mái hơn cho các dự án web hiện đại.

Tính năng nổi bật của Vite

  • Khởi động server tức thì.
  • HMR nhanh.
  • Hỗ trợ TypeScript, JSX, CSS…
  • Tối ưu hóa bản dựng
  • Plugin phổ biến
  • Đầy đủ API

Dưới đây là hướng dẫn chi tiết cách cài Bootstrap 5 trong Laravel 9 với Vite.

Cách cài đặt Bootstrap 5 trong Laravel 9 bằng Vite

Làm theo các bước sau để cài Bootstrap 5 trong Laravel 9 với Vite:

Bước 1: Cài đặt Laravel Project.

Để cài đặt ứng dụng laravel mới, tới terminal, nhập lệnh sau và tạo app laravel mới:

composer create-project --prefer-dist laravel/laravel:^9.0 laravel9-bootstrap5-vite

Hoặc nếu bạn đã cài Laravel Installer dưới dạng phần phụ thuộc composer chung:

laravel new laravel9-bootstrap5-vite

Bước 2: Cài đặt Laravel UI cho Bootstrap 5

Tiếp theo, bạn cần chạy lệnh bên dưới trong terminal

composer require laravel/ui

Bước 3: Thiết lập Auth Scaffolding với Bootstrap 5

php artisan ui bootstrap --auth

Bước 4: Cài đặt các phần phụ thuộc NPM

Chạy lệnh sau để cài đặt các phần phụ thuộc frontend:

npm install

Bước 5: Nhập đường dẫn Bootstrap 5 và vite.config.js

Đầu tiên, bạn cần thay đổi vite.config.js và thêm đường dẫn Bootstrap 5 & loại bỏ các nguồn/css/app.css.

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

export default defineConfig({
    plugins: [
        laravel([
            'resources/js/app.js',
        ]),
    ],
    resolve: {
        alias: {
            '~bootstrap': path.resolve(__dirname, 'node_modules/bootstrap'),
        }
    },
});

Bước 6: Update bootstrap.js

Chúng ta cần dùng import thay cho require.

import loadash from 'lodash'
window._ = loadash


import * as Popper from '@popperjs/core'
window.Popper = Popper

import 'bootstrap'


/**
 * We'll load the axios HTTP library which allows us to easily issue requests
 * to our Laravel back-end. This library automatically handles sending the
 * CSRF token as a header based on the value of the "XSRF" token cookie.
 */

import axios from 'axios'
window.axios = axios

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';

/**
 * Echo exposes an expressive API for subscribing to channels and listening
 * for events that are broadcast by Laravel. Echo and event broadcasting
 * allows your team to easily build robust real-time web applications.
 */

// import Echo from 'laravel-echo';

// window.Pusher = require('pusher-js');

// window.Echo = new Echo({
//     broadcaster: 'pusher',
//     key: process.env.MIX_PUSHER_APP_KEY,
//     cluster: process.env.MIX_PUSHER_APP_CLUSTER,
//     forceTLS: true
// });

Bước 7: Nhập Bootstrap 5 SCSS trong thư mục JS

Giờ bạn cần nhập đường dẫn Bootstrap 5 SCSS trong resources/js/app.js hoặc resources/js/bootstrap.js

import './bootstrap';

import '../sass/app.scss'

Bước 8: Thay thế mix() bằng lệnh Blade @vite

Khi dùng Vite, bạn cần dùng lệnh Blade @vite thay cho mix(). Loại bỏ nó và têm lệnh @vite.

<link rel="stylesheet" href="{{ mix('css/app.css') }}">
<script src="{{ mix('js/app.js') }}" defer></script>

Dùng lệnh @vite:

@vite(['resources/js/app.js'])

views/layouts/app.blade

<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <!-- CSRF Token -->
    <meta name="csrf-token" content="{{ csrf_token() }}">

    <title>{{ config('app.name', 'Laravel') }}</title>

    <!-- Fonts -->
    <link rel="dns-prefetch" href="//fonts.gstatic.com">
    <link href="https://fonts.googleapis.com/css?family=Nunito" rel="stylesheet">

    @vite(['resources/js/app.js'])

</head>
<body>
    <div id="app">
        <nav class="navbar navbar-expand-md navbar-light bg-white shadow-sm">
            <div class="container">
                <a class="navbar-brand" href="{{ url('/') }}">
                    {{ config('app.name', 'Laravel') }}
                </a>
                <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="{{ __('Toggle navigation') }}">
                    <span class="navbar-toggler-icon"></span>
                </button>

                <div class="collapse navbar-collapse" id="navbarSupportedContent">
                    <!-- Left Side Of Navbar -->
                    <ul class="navbar-nav me-auto">

                    </ul>

                    <!-- Right Side Of Navbar -->
                    <ul class="navbar-nav ms-auto">
                        <!-- Authentication Links -->
                        @guest
                            @if (Route::has('login'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('login') }}">{{ __('Login') }}</a>
                                </li>
                            @endif

                            @if (Route::has('register'))
                                <li class="nav-item">
                                    <a class="nav-link" href="{{ route('register') }}">{{ __('Register') }}</a>
                                </li>
                            @endif
                        @else
                            <li class="nav-item dropdown">
                                <a id="navbarDropdown" class="nav-link dropdown-toggle" href="#" role="button" data-bs-toggle="dropdown" aria-haspopup="true" aria-expanded="false" v-pre>
                                    {{ Auth::user()->name }}
                                </a>

                                <div class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
                                    <a class="dropdown-item" href="{{ route('logout') }}"
                                       onclick="event.preventDefault();
                                                     document.getElementById('logout-form').submit();">
                                        {{ __('Logout') }}
                                    </a>

                                    <form id="logout-form" action="{{ route('logout') }}" method="POST" class="d-none">
                                        @csrf
                                    </form>
                                </div>
                            </li>
                        @endguest
                    </ul>
                </div>
            </div>
        </nav>

        <main class="py-4">
            @yield('content')
        </main>
    </div>
</body>
</html>

Bước 9: Chạy lệnh Vite để xây dựng file Asset

Bạn cần lệnh npm run build để tạo asset bootstrap 5.

npm run build

Bước 10: Bắt đầu mở server Local

Giờ mở một terminal mới và chạy lệnh sau từ terminal của bạn để chạy server lập trình.

php artisan serve

Và điều hướng tới link sau: http://localhost:8000/

Thế là xong. Hi vọng bài viết hữu ích với các bạn.

Tag: Laravel 9, Bootstrap, lập trình Laravel, lập trình với Bootstrap, cài đặt Bootstrap, cài Bootstrap trong Laravel, Vite

Thứ Sáu, 20/01/2023 05:51
31 👨 1.113
0 Bình luận
Sắp xếp theo