Uncaught ReferenceError: $ is not defined

4

I do not know why I get that error if jQuery is the first library I import, I'm working with Laravel and this is what I have in my app.js file

import jQuery from 'jquery'

import My_Script from './script/myscript.js'

and in the wlcome.blade.php view I import the script

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

the error marks it in my script in the function:

$(document).on("ready", function () {
});

already verify that jQuery is in the app.js file and that it is before my script

    
asked by Roman González 02.04.2018 в 03:16
source

2 answers

4

The "good practice" to import jQuery is to import both $ as jQuery to be able to use it in both ways, and later, make it available for other scripts by adding it to window:

import {$,jQuery} from 'jquery';

window.$ = $;
window.jQuery = jQuery;
    
answered by 02.04.2018 / 03:42
source
1

Another option would be to download the JQuery library, store it in your public / js and then invoke it as follows:

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

In the same way you can help the helper asset to be laravel   which autocomplete the absolute path and when you open your project the   library and the app file load immediately

If you do not want to do it that way, use the library itself from a CDN like the following:

<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>

Any of the above options to ensure that when you open your project the file is loaded correctly

    
answered by 02.04.2018 в 03:30