5

I get an error when try to import jquery in laravel VITE, jquery seems to be loaded in my compiled javascript:

       Uncaught TypeError: window.$ is not a function
    at dashboard:1823:12
(anonimo) @ dashboard:1823
[Violation]Forced reflow while executing JavaScript took 72ms
dashboard:101 
 
        
       Uncaught Error: Bootstrap's JavaScript requires jQuery
    at app.0bbf2228.js:50:31

App.js is:

import vue from "vue";
window.Vue = vue;


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

import './bootstrap';

2 Answers 2

11

jQuery does support ESM, it's stated in the README on their npm package page, scroll to the Including jQuery section, and babel.

import $ from "jquery";
window.$ = $;

What is most likely the issue is you are trying to access $ on the window object before it has been loaded in. Laravel loads its scripts as JavaScript modules which are deferred by default.

So if you're trying to access jQuery using a blocking inline <script> tag, jQuery won't be available when the browser executes that JavaScript.

If you want to use jQuery in inline <script> tags, then use inline JavaScript modules instead, and add them after your @vite Blade directive.

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

<script type="module">
$('h1').text('Hello, World')
</script>
Sign up to request clarification or add additional context in comments.

2 Comments

What is the second script is also using @vite('...') to include the script?
I was missing the type="module" attribute setting on script.
1

Found an answer here:

This is because jQuery when imported in an ESM context considers itself in non-global mode and therefore does not put $ on window, but bootstrap is eagerly initialized on import and expects $ to be available on window.

This is unfortunately a case where jQuery and Bootstrap were designed without ESM in mind so they rely on implicit global coupling to work.

– Evan You on the GitHub bug report

https://www.mapledesign.co.uk/tech-blog/vite-bootstrap-4-jquery/

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.