I’m trying to import jQuery in my Laravel 9 project, which I installed with npm i jquery
I’m getting Uncaught ReferenceError: $ is not defined
in my app.blade.php
<!doctype html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Fonts -->
<link rel="dns-prefetch" href="//fonts.gstatic.com">
<!-- Scripts -->
@vite(['resources/sass/app.scss', 'resources/js/app.js'])
</head>
in my another view, which extends app.blade.php
<script>
$(function(){
alert('jquery ok');
})
</script>
in resources/js/app.js
I tried all sorts of things
import $ from 'jquery';
import $ from 'jquery';
window.jQuery = $;
window.$ = $;
import inject from '@rollup/plugin-inject';
export default {
plugins: [
// Add it first
inject({
$: 'jquery',
}),
// Other plugins...
],
// The rest of your configuration...
};
try {
window.$ = window.jQuery = require('jquery');
} catch (e) {}
Nothing works. How can I fix this?
npm – 8.11.0
node – 16.16.0
laravel/framework – 9.32.0
vite – 3.14
4
Answers
The answer to my question was to be found here ReferenceError: $ is not defined, Jquery Import with vite
Where are you importing your JQuery files? (JS and CSS)
You need something like this on your head section: (obviously you have to specify your actual path to those files)
Then you just need to use a script tag like this:
If you’d like to use javascript dynamic imports because some pages may not require jQuery.
Build tools/bundlers like ViteJs, WebPack, Laravel Mix and others support this.
Inside your
app.js
You could put the import in side an if statement
In any page that requires jQuery you could add
class="useJquery"
.Then only pages with the
useJquery
class will download JQuery.For me the problem was on how the libraries are imported on the
bootstrap.js
. I changed the file:Now you can use