Laravel 5 WebPack JQuery - $ is not defined

前端 未结 4 845
慢半拍i
慢半拍i 2021-01-05 09:08

I Have webpack.min.js:

mix.webpackConfig(webpack => {
    return {
        plugins: [
            new webpack.ProvidePlugin({
                $: \'jquery\         


        
相关标签:
4条回答
  • 2021-01-05 09:55

    I had this issue in Laravel 5.7 when I tried using some of the default views that it provided. I was trying to use JavaScript (which required using jQuery) in some blade view templates that extended the default layout/app.blade.php template.

    But for me the problem was not the window.$ not being assigned the window.jQuery library, because it was being added as far as the resources/js/bootstrap.js file was concerned. (This is a file that appears to be precompiled into public/js/app.js by Laravel Mix. You can see this is the case by looking into webpack.mix.js, within it, you'll find this statement:

    mix.js('resources/js/app.js', 'public/js')

    where

    resources/js/app.js requires resources/js/bootstrap.js .

    If you wish to manually compile this for yourself first run:

    npm install then npm run dev when in development mode, or npm run prod when in production mode.

    but anyways (I've digressed) ....

    It turned out that the issue was here:

    resources/views/layouts/app.blade.php

    There was an instance of script tag with a defer attribute like so:

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

    That defer attribute was causing all the problems.

    So I removed it like so:

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

    and the problem of jQuery not being defined was solved.

    I prefer to defer my JavaScript loading by simply moving the script tags closer to the end of body HTML tag anyways.

    0 讨论(0)
  • 2021-01-05 10:06

    I use mix.copy instead mix.js for jQuery and it works great!

    example:

    mix.copy('node_modules/jquery/dist/jquery.min.js', 'public/vendor/jquery/jquery.min.js');
    
    0 讨论(0)
  • 2021-01-05 10:08

    Try this in your main.js file

    global.$ = global.jQuery = require('jquery');
    
    0 讨论(0)
  • 2021-01-05 10:10

    in app.blade.php  

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

    remove defer so make it

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

    https://github.com/laravel/framework/issues/17634#issuecomment-375473990

    0 讨论(0)
提交回复
热议问题