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
CodePudding user response:
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)
<link href="./jquery-files/jquery-ui.css" rel="stylesheet">
<script src="./jquery-files/external/jquery/jquery.js"></script>
<script src="./jquery-files/jquery-ui.min.js"></script>
Then you just need to use a script tag like this:
<script type="text/javascript">
$().ready(function () {
//add all JQuery related code here!!
alert('jquery ok'); //this will show an alert when the page is loaded
});
</script>
CodePudding user response:
The answer to my question was to be found here ReferenceError: $ is not defined, Jquery Import with vite
<script type="module"> //type="module" is the important part
$(function () {
alert('jquery ok');
})
</script>