'Laravel Mix Uncaught ReferenceError: $ is not defined

I've searched and searched and I can't find the answer to my problem on SO. So here's my issue. I'm trying to load jQuery Globally using Laravel Mix. I've tried modifying all sorts of files, and nothing seems to be working... I'm still getting the "$ is not defined" error.

Here's my code.

Bootstrap.js

window._ = require('lodash');
window.Popper = require('popper.js').default;

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

    require('bootstrap');
} catch (e) {}

window.axios = require('axios');

window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';


let token = document.head.querySelector('meta[name="csrf-token"]');

if (token) {
    window.axios.defaults.headers.common['X-CSRF-TOKEN'] = token.content;
} else {
    console.error('CSRF token not found: https://laravel.com/docs/csrf#csrf-x-csrf-token');
}

webpack.mix.js

mix.js('resources/assets/js/app.js', 'public/js')
   .js('resources/assets/js/select2.min.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css')
   .sass('resources/assets/sass/admin/app.scss', 'public/css/admin')
   .copy('resources/assets/css/fontawesome.css', 'public/css')
   .copy('resources/assets/css/select2.min.css', 'public/css')
   .copy('resources/assets/webfonts', 'public/webfonts')
   .copy('resources/assets/js/tinymce', 'public/js/tinymce');

mix.browserSync('http://localhost:8000');

Error I'm getting:

Error Screenshot

Uncaught ReferenceError: $ is not defined

Code on inside of create.blade.php in the @section('scripts')

<script>
   $(function(){
        alert();
    });
</script>
{{-- Tiny MCE --}}
<script src="/js/tinymce/tinymce.min.js"></script>
<script>
    tinymce.init({
        selector:'textarea',
        plugins: 'link',
        menubar: false,
        branding: false,
        resize: false,
        statusbar: false,
        force_br_newlines : false,
        force_p_newlines : false,
        forced_root_block : '',
        toolbar:    ['undo redo | cut copy paste | removeformat',
                    'bold italic underline | link | outdent indent | alignleft aligncenter alignright alignjustify alignnone',],
    });
</script>

{{-- Image Javascript --}}
<script type="text/javascript">
    $(function() {

        // We can attach the `fileselect` event to all file inputs on the page
        $(document).on('change', ':file', function() {
            var input = $(this),
            numFiles = input.get(0).files ? input.get(0).files.length : 1,
            label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
            input.trigger('fileselect', [numFiles, label]);
        });

        // We can watch for our custom `fileselect` event like this
        $(document).ready( function() {
            $(':file').on('fileselect', function(event, numFiles, label) {

            var input = $(this).parents('.input-group').find(':text'),
            log = numFiles > 1 ? numFiles + ' files selected' : label;

            if( input.length ) {
                input.val(log);
            } else {
                if( log ) alert(log);
            }

            });
        });

    });
</script>

AND finally my layout file

<!-- Scripts -->
        <script src="{{ asset('js/app.js') }}" defer></script>

        {{-- Page Specific Scripts --}}
        @yield('scripts')

    </body>

What am I doing wrong?!?!?

Console.log(e) returns nothing... which means jquery should be loading correctly but isn't.

this is the app.js file

Still giving same error



Solution 1:[1]

If you use jquery in laravel mix, import this way in your app.js:

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

Solution 2:[2]

I had the same problem on Laravel 6. You can do two things...

Or remove de defer from the script tag;

<script src=”{{ asset(‘js/app.js’) }}” defer></script>

Should be:

<script src=”{{ asset(‘js/app.js’) }}"></script>

Or use jQuery after load event in your Blade template like this;

<script>
window.addEventListener('load', function() {
   console.log($);
});
</script>

The defer attribute in a script tag is used when you want the script to be executed after the page has been parsed completely. So you can only make use of the loaded script once the page is loaded and the script is completely loaded.

Solution 3:[3]

I had the same errors with jquery in laravel. I have solved it by installing jquery via npm npm install jquery then I have imported jquery in the script that I need, like so:

import $ from "jquery";

then $ will be available in the js file. After that I have called my js file in entry-point.js and run npm run dev

Solution 4:[4]

What worked for me,

  1. First ensure that you have installed 'jQuery'

npm install --save jquery

  1. Next what @orangeman suggested - in app.js - as the first statement @courtesy Orange-Man

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

  1. Then, running the following command

npm install && npm run dev

Hope it helps!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Mahdi Bashirpour
Solution 2 Daantje
Solution 3 Ildar Nasurlaev
Solution 4 Jay Pagnis