Ad

"$ Is Not Defined" When Using $ In View After Requiring It In App.js

- 1 answer

I have an app and want to use Jquery in script tags inside my views.

I've tried moving the imports and making sure the app.js with the require jquery is loaded BEFORE the other script does (with alerts, one right after the importation, one right before the jquery I want to use).

I guess I could make one file per view and change my webpack config and require each time jquery, but that would be bothersome.

app.js

window._ = require('lodash');
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('bootstrap');

login.blade.php (layout)

<head>
    <!-- Scripts -->
    <script src="{{ asset('js/app.js') }}"></script>
    <script>
        $(document).ready(function () {
            alert("jQuery loaded");
        });
    </script>
</head>

webpack.mix.js

mix.autoload({
    jquery: ['$', 'window.jQuery', "jQuery", "window.$", "jquery", "window.jquery"],
    'popper.js/dist/umd/popper.js': ['Popper']
}).js('resources/js/app.js', 'public/js', 'ressources/js/password.js')
    .sass('resources/sass/app.scss', 'public/css');

I expect an alert saying jQuery loaded but got an

"Uncaught ReferenceError: $ is not defined"

Ad

Answer

In my app.js requirement I changed

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

to

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

If someone has the reason as to why this does work (and maybe why I shouldn't do that), I'd be happy to hear it.

Ad
source: stackoverflow.com
Ad