Laravel 9 Install Bootstrap 5 via Vite

Sovary August 12, 2022 887
6 minutes read

In early version Laravel by default come with Laravel-Mix which is front-end tool to install UI Framework, but for latest version Laravel use next generation of front-end tool which is Vite. Today we will learn how to install Boostrap 5 using Vite. I will guide you step by step to install Bootstrap with Vite.

Before we dive to the topic what is Bootstrap? some of you may know already.

What is Bootstrap?

Boostrap is front-end web development framework which is open source and free. The style CSS boost your development UI speed and responsive design by provide collection syntax CSS for template design. You may read document Bootstrap

What is Vite?

Vite is a rapid development tool for modern web projects that aims to focus on speed and performance. You may read document Vite

With major changed Laravel 9 has no more webpack.mix.js in root Laravel directory. You may find vite.config.js instead of webpack.mix.js file is replaced.

Installation Bootstrap 5 in Laravel 9 via Vite

The following step to install Bootstrap 5 in Laravel 9 via Vite.

  • Step 1 - Download Laravel Project
  • Step 2 - Install Laravel UI & Auth Scaffolding
  • Step 3 - Import Bootstrap 5 Path in vite.config.js
  • Step 4 - Update Bootstrap.js File
  • Step 5 - Import Bootstrap 5 SCSS
  • Step 6 - Replace mix() with @vite Directive
  • Step 7 - Install NPM Dependencies
  • Step 8 - Build Asset File
  • Step 9 - Run Laravel Server

Step 1 - Download Laravel Project

You have to installed Laravel framework. Read this to know how to install Laravel project, but in this case we don't required database configuration.

Step 2 - Install Laravel UI & Auth Scaffolding

Launch terminal and type command below to install UI and generate authentication page which is support designing style:

composer require laravel/ui
php artisan ui bootstrap --auth

Step 3 - Import Bootstrap 5 Path in vite.config.js 

We will modified vite.config.js with bootstrap 5 path and remove resources -> css -> app.css

Open file vite.config.js

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'),
        }
    },
});

Step 4 - Update Bootstrap.js File

We have to use import instead of require. See below code where to changed: resources/js/bootstrap.js

import loadash from 'lodash'
window._ = loadash

/**
 * 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
// });

Step 5 - Import Bootstrap 5 SCSS

This step we are going to import Bootstrap 5 SCSS to js file.

Open file resources -> js -> app.js

import './bootstrap';

import '../sass/app.scss'

import * as bootstrap from 'bootstrap'

Step 6 - Replace mix() with @vite Directive

We have to remove mix helper with @vite directive syntax.

Open file views -> layouts -> app.blade

Remove the lines

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

and use @vite directive

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

 Full snippet code:

<!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">

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

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

Step 7 - Install NPM Dependencies

To run below command you have to install Node.js first. In my case I use Node.js version v17.4.0. After install Node.js you may run below command:

npm install

Step 8 - Build Asset File

We are going to run command to create asset bootstrap 5. Run below command:

npm run build

Step 9 - Run Laravel Server

Run following command to start Laravel server

php artisan serve

Open the browser with URL http://localhost:8000/login to see if the UI style work properly.

Hope this article help you. Feel free to comment below, if you have any query. Have a nice day!

You might Also Like:

 

Laravel  PHP 
Author

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him