How to Install jQuery in Laravel With Vite

jQuery is a powerful JavaScript library, which simplifies browser scripting and helps make your web application more interactive.

Starting with Laravel 8, Vite has been included as the default build tool. Using Vite to compile your CSS and JS, including dependencies such as jQuery, helps optimize and minify your assets.

In this tutorial, we’ll guide you through the process of installing jQuery using npm, compiling it into your public assets folder, and using the Blade directive @vite to include it in your Blade template. Finally, we’ll demonstrate a simple application of jQuery by changing the color of a paragraph upon clicking.

Let’s get started!

Step 1: Create a New Laravel Project

First, let’s create a new Laravel project if you don’t already have one. Open your terminal and run the following command:

composer create-project laravel/laravel laravel-jquery-vite

Navigate to your project directory:

cd laravel-jquery-vite

Step 2: Install jQuery Using npm

In your Laravel project, you can use npm to manage your JavaScript libraries. Let’s install jQuery by running the following command:

npm install jquery

Step 3: Add jQuery import to app.js

Open the resources/js/app.js file and add the following line to import jQuery, right after the standard Laravel bootstrap import:

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

import jQuery from 'jquery';
window.$ = jQuery;

Step 4: Install jQuery in Your Blade Templates

Now, let’s include jQuery in your Blade templates. Create a blade file and add the example code shown below:

resources/views/test-jquery.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Laracoding.com - Including jQuery with Vite</title>
    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<body>
    <p class="zoomable">
        Click me to zoom
    </p>
    <script type="module">
        $(document).ready(function(){
            $(".zoomable").click(function(){
                $(this).animate({
                    fontSize: "40px"
                }, 1000);
            });
        });
    </script>
</body>
</html>

Note that we use the @vite directive to generate the correct URIs to our JS and CSS files in the public folder. Also, note that we use <script type="module"> tags on scripts that rely on jQuery being loaded and ready to use. If we don’t load it as a module you will see an error. Read more about why this happens in the FAQ: How to Fix ReferenceError: $ is not defined

Step 5: Add a Route

In your Laravel application, you need a route to render this view. Open routes/web.php and add the following route:

routes/web.php
<?php

use Illuminate\Support\Facades\Route;

// .. other routes

Route::get('/test-jquery', function () {
    return view('test-jquery');
});

Step 6: Compile Your Assets Using npm

Now, it’s time to compile your assets. Laravel Vite makes this process easy. To compile assets for development, use:

npm run dev

The primary benefit of using npm run dev is that Vite automatically detects changes in your .js and .css files, rebuilds your assets into the ‘public’ folder, and refreshes them in the browser using Hot Module Replacement (HMR), eliminating the need for manual refreshing.

For production, use:

npm run build

The main reason for using npm run build instead of npm run dev is that Vite will minify and optimize your assets automatically, helping to reduce file sizes.

Your Laravel application is now ready to use jQuery!

Step 7: Test the Application

To test your application, start the Laravel development server:

php artisan serve

Your Laravel application with jQuery and Vite is now ready to use. Open your browser and navigate to http://127.0.0.1:8000/test-jquery to see the result.

That’s it! You’ve successfully installed and used jQuery with Laravel Vite. This combination allows you to efficiently manage your assets and enhance interactivity on your web applications.

Frequently Asked Questions

How to Fix ReferenceError: $ is not defined When Importing jQuery With Vite

The ‘ReferenceError: $ is not defined’ error occurs because Vite loads scripts as modules, and module scripts are loaded deferred. If your jQuery script is placed after the Vite directive, the jQuery code executes before jQuery is properly loaded into the window. This is what triggers the error.

To fix this issue, ensure that you include your JavaScript code within a <script> tag with the attribute type="module". Here’s an example:

<head>
    <!-- other code inside head ... -->
    @vite(['resources/css/app.css', 'resources/js/app.js'])
</head>
<html>
<body>
    <!-- other code inside body ... -->
    <script type="module">
        $('p').click(function(){
            $(this).css('background-color', '#ff0000'); // Turn clicked paragraph text red using jQuery
        });
    </script>
</body>
</html>

How Can I Update My jQuery Version Using Vite?

One advantage of using Vite for asset management is its ease of updating dependencies. Now, when jQuery releases a new version, you can update and recompile your assets by running these simple commands:

npm update jquery
npm run build

That’s it! You’re now using the most recent jQuery version.

Conclusion

Adding jQuery into your Laravel application opens up many possibilities for building interactive pages.

By using Vite to pull the required files allows for an easy installation, updates, optimization and minification of your assets throughout your application’s lifecycle.

Now go ahead and build jQuery into your own application’s assets and make something great. Happy coding!

References

This entry is part 2 of 5 in the series Installing Laravel Assets Using Vite

  1. How to Install Font Awesome in Laravel With Vite
  2. How to Install jQuery in Laravel With Vite
  3. How to Install Bootstrap in Laravel With Vite
  4. How to Install TinyMCE in Laravel With Vite
  5. How to Add Custom JavaScript to Laravel With Vite

Johan van den Broek

Johan is the creator of laracoding.com. As a child, he began tinkering with various programming languages, many of which have been long forgotten today. Currently, he works exclusively with PHP and Laravel, and his passion for programming remains to this day.

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts