Laravel Mix Uncaught ReferenceError: $ is not defined
Asked Answered
J

5

8

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

Jenisejenkel answered 16/8, 2018 at 4:41 Comment(7)
Catch the error ..?Penchant
from a brief look, try maybe wrapping your code with on load without depending on jQuery. Maybe it breaks on that pointAgrimony
@Penchant how would i do that?Jenisejenkel
?? You've wrapped jQuery loading into try..catch, why not log the error message, if there happens to be a one.Penchant
That try catch was already there... i didn't write that... it came with laravel already installedJenisejenkel
Change the catch block to catch (e) { console.log(e); } and see what/if there is an error in the console.Fated
Still gives the same error. Nothing logged out. See attached pics above.Jenisejenkel
S
8

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

window.$ = window.jQuery = require('jquery');
Slapstick answered 20/4, 2019 at 7:44 Comment(2)
That does no longer work in laravel 6. I have in bootstrap.js line: try { window.Popper = require('popper.js').default; window.$ = window.jQuery = require('jquery'); require('bootstrap'); } catch (e) {} and still have that problemBiblioclast
@Biblioclast try change it to global.$ = global.jQuery = require('jquery');Casillas
P
10

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.

Protectionist answered 2/7, 2020 at 12:31 Comment(0)
S
8

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

window.$ = window.jQuery = require('jquery');
Slapstick answered 20/4, 2019 at 7:44 Comment(2)
That does no longer work in laravel 6. I have in bootstrap.js line: try { window.Popper = require('popper.js').default; window.$ = window.jQuery = require('jquery'); require('bootstrap'); } catch (e) {} and still have that problemBiblioclast
@Biblioclast try change it to global.$ = global.jQuery = require('jquery');Casillas
C
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

Carpeting answered 18/2, 2021 at 11:52 Comment(0)
E
1

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!

Eloign answered 23/4, 2022 at 6:9 Comment(0)
B
0

I had a different solution, so I am sharing in case anyone runs into the same issue as me. I was using

 mix.js("resources/js/app.js", "public/dist/js")
    .vue()
    .sass("resources/sass/app.scss", "public/dist/css")
    .extract();

on my webpack.mix.js file, but on the layouts.app file, I was incorrectly importing as so:

    <script src="{{ mix('dist/js/app.js') }}"></script>

when the correct import script is this:

    <script src="{{ mix('dist/js/app.js') }}"></script>
    <script src="{{ mix('dist/js/manifest.js') }}"></script>
    <script src="{{ mix('dist/js/vendor.js') }}"></script>

This is necessary because when you use the extract() function, your js files and the vendor files are divided into different files, so by not including them, $ was undefined.

Bunton answered 20/11, 2023 at 16:22 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.