skip to Main Content

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


  1. Chosen as BEST ANSWER

    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>
    

  2. 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>
    
    Login or Signup to reply.
  3. 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

    async function main() {
      const { default: jQuery } = await import('jquery')
      window.jquery = window.jQuery = window.$ = jQuery;
    
      // code that uses jQuery
      console.log('jQuery v', $().jquery);
    }
    
    main();
    

    You could put the import in side an if statement

    async function main() {
    
      if (document.querySelector('.useJquery')) {
        const { default: jQuery } = await import('jquery')
        window.jquery = window.jQuery = window.$ = jQuery;
    
        // code that uses jQuery
        console.log('jQuery v', $().jquery);
      }
    }
    

    In any page that requires jQuery you could add class="useJquery".

    Then only pages with the useJquery class will download JQuery.

    Login or Signup to reply.
  4. For me the problem was on how the libraries are imported on the bootstrap.js. I changed the file:

    import _ from 'lodash';
    // Since I'm using jquery from admin-lte 🤷 
    import $ from 'admin-lte/plugins/jquery/jquery';
    import * as Popper from 'popper.js';
    // Since I'm using jquery from admin-lte 🤷 
    import 'admin-lte/plugins/bootstrap/js/bootstrap'
    window._ = _;
    window.Popper = Popper.defaults;
    window.$ = window.jQuery = $;
    

    Now you can use

    <script type="module">
        $(function () {
            console.log('Jquery loaded');    
        });
    </script>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search