I have a laravel 10 project, I am trying to use a jQuery plugin but get the error
"jQuery is not defined" from the plugin..
Without the plugin js included I get no errors and the jQuery function works.
In the blade I am using this , which works so jQuery is loading.
<script type="module">
var csrf_token = '{{csrf_token()}}';
var selectedAvatar = '';
$(function() {
$('.avatar').click(function(event){
selectedAvatar = event.target.getAttribute('data-avatar');
selectedAvatar = selectedAvatar.replace('"','').trim();
$('#avatar-large').attr("src","/uploads/avatars/"+selectedAvatar);
});
});
In my app.js I have
import './bootstrap';
import Alpine from 'alpinejs';
window.Alpine = Alpine;
Alpine.start();
import jQuery from 'jquery';
window.$ = jQuery;
and in my vite.config.js it looks like
import { defineConfig } from 'vite';
import laravel from 'laravel-vite-plugin';
export default defineConfig({
plugins: [
laravel({
input: [
'resources/css/app.css',
'resources/js/app.js',
],
refresh: true,
}),
],
resolve: {
alias: {
'$': 'jQuery'
},
}
});
But as soon as i add the
<script type="text/javascript" src="/jsvendor/tablesorter/js/jquery.tablesorter.js"></script>
I get the Error
Uncaught ReferenceError: jQuery is not defined
2
Answers
Ending up being two things.
<script type="module"> instead of <script type="text/javascript">
thanks Tim Lewis
but i also had to change
to
This is likely caused due scoping.
You can try in your app.js file, instead of assigning jQuery to window.$, use the
globalThis.$ = jQuery
syntax.This makes jQuery available globally for all scripts, including your plugin.
this should solve your issue.