I tried with fresh install laravel 9.20 and with minimum configuration
in vite.config.js
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
export default defineConfig({
plugins: [
laravel({
input: [
'resources/js/app.js',
],
refresh: true,
}),
],
});
in app.js
import './bootstrap';
import $ from "jquery";
window.$ = window.jQuery = $;
import '../sass/app.scss';
i have tried with this too
import * as $ from "jquery";
window.$ = window.jQuery = $;
load the assets in blade and i test with this script
@vite(['resources/js/app.js']);
$("#alertbox").alert("test");
but i get the following error in the console:
Uncaught ReferenceError: $ is not defined
I can't make it work, please help
This happens because of Vite's module loading order. You're seeing a race condition, and it's not an issue with the import.
To confirm this, try calling the jQuery code after a timeout as below.
<script>
setTimeout(function() {
console.log($);
$("#alertbox").alert("test");
}, 5000);
</script>
If there's no error with the above, then it means the code is getting executed in the incorrect order. But adding a timeout is not a good way to solve it, so let's look at the cause of the problem.
If you look at source code you'll see something like this.
<script type="module" src="http://localhost/build/assets/app.342432.js"></script>
This means Vite is loading scripts as modules. And module scripts are always deferred. So if your jQuery script is placed after Vite directive, jQuery code is executed first, before loading jQuery to window - this triggers $ is undefined error.
In best practise, you should move the jQuery code to app.js file, so it stays in it's own module. The other way to handle this is to mark your script tag as a module, then it'll follow the loading order of the document.
Change the script tag as below.
@vite(['resources/js/app.js']);
<script type="module">
$("#alertbox").alert("test");
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With