For some reason my jQuery refuses to load. I am getting an error:
ReferenceError: $ is not defined
My template is in views/layouts/editor.blade.php
and I am loading jQuery in the head of my template like this
<script src="{{ asset('js/jquery.min.js') }}"></script>
I can see that jQuery is loaded in my console. but still I get the error.
I am compiling my javascript using laravel mix and my webpack.mix.js file looks like this:
// javascript
mix.js('resources/assets/js/app.js', 'public/js')
.js('node_modules/jquery/dist/jquery.min.js', 'public/js')
.autoload({
jquery: ['$', 'window.jQuery', 'jQuery'],
});
// css
mix.sass('resources/assets/sass/app.scss', 'public/css')
.sass('node_modules/bootstrap/scss/bootstrap.scss', 'public/css');
Why is this happening?
EDIT:
My template file looks like this:
<!DOCTYPE html>
<html lang="{{ app()->getLocale() }}">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- CSRF Token -->
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>{{ config('app.name', 'Laravel') }}</title>
<!-- Styles -->
<link href="{{ asset('css/bootstrap.css') }}" rel="stylesheet">
<link href="{{ asset('css/app.css') }}" rel="stylesheet">
<!-- scripts -->
<script src="{{ asset('js/jquery.min.js') }}"></script>
<script>
$(function(){
alert();
});
</script>
</head>
<body>
@yield('content')
<!-- Scripts -->
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
If I look in my console I see the following
If I open the jquery.min.js file in a new tab I see the following:
So it's jquery underneath all that webpack boilerplate stuff.
I have also run npm run production
which removes all that webpack stuff and leaves the raw jquery.
Try this. In your view file create a section under content section
@section('scripts')
<script src="{{ asset('js/jquery.min.js') }}"></script>
<script>
$(function(){
alert();
});
</script>
<script src="{{ asset('js/app.js') }}"></script>
@endsection
Then @yield('scripts') just under the @yield('content') in your template file. So its looks like
<body>
@yield('content')
<!-- Scripts -->
@yield('scripts')
</body>