KodaC's avatar
Level 1

jQuery with vite $/jQuery is not a function

I have installed jQuery with npm and imported the library in app.js.

import "jquery/dist/jquery.min.js";

I have also tried to add the following to app.js

import $ from "jquery";

I have added the app.js to the header of my Blade

@vite(['resources/sass/app.scss', 'resources/js/app.js'])

After running npm run build, I see in the source code that jQuery has been integrated into the header.

But as soon as I call a jQuery with $ or jQuery in the footer I always get the error

Uncaught TypeError: $ (or jQuery) is not a function at....
0 likes
3 replies
LaryAI's avatar
Level 58

It looks like you're importing jQuery correctly, but you need to make sure it's available in the global scope so that you can use the $ or jQuery functions in your footer.

Try adding the following line to your app.js file after importing jQuery:

window.$ = window.jQuery = require('jquery');

This will make jQuery available globally, so you can use it in your footer.

Alternatively, you can use the expose option in your vite.config.js file to make jQuery available globally without having to modify your app.js file:

export default {
  // ...
  build: {
    rollupOptions: {
      output: {
        // expose jQuery as a global variable
        globals: {
          jquery: 'jQuery'
        }
      }
    }
  }
}

Then, in your app.js file, you can import jQuery like this:

import 'jquery';

And in your footer, you can use $ or jQuery without any errors.

KodaC's avatar
Level 1

Thank you

The one with vite.conf.js doesn't seem to work, and the other one gives me the error "Uncaught ReferenceError: require is not defined".

Zuby's avatar

I am having this same problems. The funny thing is that its all working fine in the original code. Made a copy to deploy the app for someone else and this issue has cropped up.

Please or to participate in this conversation.