skip to Main Content

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


  1. Chosen as BEST ANSWER

    Ending up being two things.

    1. <script type="module"> instead of <script type="text/javascript">

    thanks Tim Lewis

    1. but i also had to change

      window.$ = jQuery;
      

    to

       window.$ = window.jQuery = jQuery;
    

  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search