2

I use Laravel 5.6, I removed Vue.JS to use jQuery on my project. I can use jQuery in my JS files, but I can't use it in my template.

I created an yield to put Javascript, this yield is loaded at the end of the page.

I looked at app.js and bootsrap.js default files, it seems that jQuery is loaded in boostrap :

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

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

I tried to define the global in my app.js :

let $ = require('jquery');
// create global $ and jQuery variables
global.$ = global.jQuery = $;

And I put this in my webpack.mix.js :

mix.autoload({
    jQuery: 'jquery',
    $: 'jquery',
    jquery: 'jquery'
});

I got no errors, I just can't use $ or jQuery in my blade templates, I have this message :

Uncaught ReferenceError: $ is not defined

In Symfony 4, I only put the global $ in app.js, and it works. What do I miss ?

My app.js :

require('./bootstrap');
require('./custom-checkboxes');

$(function() {
    $('body').click(function(e) {
        // it works
    });
});

My webpack.min.js :

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css')
   .sass('resources/assets/sass/pages/homepage.scss', 'public/css')
   .sass('resources/assets/sass/pages/calendar.scss', 'public/css')
;
mix.autoload({
    jQuery: 'jquery',
    $: 'jquery',
    jquery: 'jquery'
});

mix.copyDirectory('resources/assets/img', 'public/img');

if (mix.inProduction()) {
    mix.version();
}

My bootstrap.js :

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

/**
 * We'll load jQuery and the Bootstrap jQuery plugin which provides support
 * for JavaScript based Bootstrap features such as modals and tabs. This
 * code may be modified to fit the specific needs of your application.
 */

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

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

....
miken32
  • 42,008
  • 16
  • 111
  • 154
Vincent Decaux
  • 9,857
  • 6
  • 56
  • 84

1 Answers1

0

I had the same issue. What I did was remove the defer property from the script tag that refer to app.js file in the app.blade file and put that script tag to the bottom of the page.

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

change this to,

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

and add other js files(if needed) below it. No need to configure any other files or add external reference to jQuery as it loaded by Mix.

you can check this out too. Laravel 5 WebPack JQuery - $ is not defined