Laravel Vite - register-f03c46a4.js:5 Uncaught Error: Bootstrap's JavaScript requires jQuery

89 Views Asked by At

I must add these JS files to a compiled JS file using Laravel Vite.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> 
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-steps/1.1.0/jquery.steps.min.js"></script> 
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.js"></script>

This is my vite.config.js.

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

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

And this is resources/js/register.js

import 'jquery/dist/jquery.min.js';
import 'bootstrap/dist/js/bootstrap.min.js';
import 'jquery-steps/build/jquery.steps.min.js';
import 'jquery-validation/dist/jquery.validate.js';

var form = $("#example-form");

form.steps({
    headerTag: "h6",
    bodyTag: "section",
    transitionEffect: "fade",
    titleTemplate: '<span class="step">#index#</span> #title#'
});

I ran command npm install [email protected] [email protected] [email protected] [email protected]

But when I call

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

I get error

Uncaught Error: Bootstrap's JavaScript requires jQuery at register-f03c46a4.js:5:31

This is a GitHub repo of my code https://github.com/vimuths123/viteissue

1

There are 1 best solutions below

0
On BEST ANSWER

The error you're encountering is due to how modules are imported in ES6. When you use import, it doesn't create a global variable that libraries like Bootstrap can access.

To solve this issue, you can assign jQuery to a global variable after importing it. Here's how you can do it:

import $ from 'jquery/dist/jquery.min.js';
window.$ = window.jQuery = $;

import 'bootstrap/dist/js/bootstrap.min.js';
import 'jquery-steps/build/jquery.steps.min.js';
import 'jquery-validation/dist/jquery.validate.js';

var form = $("#example-form");

form.steps({
    headerTag: "h6",
    bodyTag: "section",
    transitionEffect: "fade",
    titleTemplate: '<span class="step">#index#</span> #title#'
});

In this code, window.$ = window.jQuery = $; assigns the imported jQuery module to the global variables $ and jQuery, which makes it accessible to other libraries like Bootstrap that require jQuery to be globally accessible.