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
Found an answer here:
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/
jQuery does support ESM, it’s stated in the README on their npm package page, scroll to the Including jQuery section, and babel.
What is most likely the issue is you are trying to access
$
on thewindow
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.