Search code examples
javascriptjquerylaravel

How to use jQuery in Laravel blade files


first of all i know there are plenty of similar questions for this, but none of them solved my problem.

I have app.js:

import $ from 'jquery';

$(document).ready(function () {
    ...
});

window.$ = $;

and my index.blade.php file:

<html>
  <head>
    @vite(['resources/js/admin/app.js', 'resources/css/admin/app.css'])
  </head>
  <body>
    ...
    
    <script type="text/javascript">
        $(document).ready(function() {
             // Throws: $ is not defined
        });
    </script>
  </body>
</html>

It never can access jquery. I've tried everything. Other libraries work fine but jQuery just don't.


Solution

  • You were so close... Vite loads JS as Modules, so you need to use <script type="module"> instead of <script type="text/javascript"> for this to work:

    <script type="module">
      $(document).ready(function() {
                 
      });
    </script>
    

    I also have this in my vite.config.js, but I'm not 100% sure it's needed:

    // ...
      resolve: {
        alias: {
          '$': 'jQuery',
        }
      }