简体   繁体   中英

Use Jquery in Laravel Vite

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';

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/

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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM