Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 WebPack JQuery - $ is not defined

I Have webpack.min.js:

mix.webpackConfig(webpack => {
    return {
        plugins: [
            new webpack.ProvidePlugin({
                $: 'jquery',
                jQuery: 'jquery',
                'window.jQuery': 'jquery',
                Popper: ['popper.js', 'default'],
            })
        ]
    };
});

mix.sass('resources/assets/styles/index.scss', 'public/css/app.css')
    .js('resources/assets/scripts/index.js', 'public/js/app.js')
    .copyDirectory('resources/assets/static', 'public/static')
    .version()
    .sourceMaps();

and package.json:

"devDependencies": {
    "jquery": "^3.3.1",
    "axios": "^0.18.0",
    "bootstrap": "^4.1.3",
    "bootstrap-datepicker": "^1.7.1",
    "browser-sync": "^2.24.6",
    "browser-sync-webpack-plugin": "^2.0.1",
    "chart.js": "^2.7.2",
    "cross-env": "^5.2.0",
    "datatables": "^1.10.18",
    "easy-pie-chart": "^2.1.7",
    "font-awesome": "4.7.0",
    "fullcalendar": "^3.9.0",
    "jquery-sparkline": "^2.4.0",
    "jvectormap": "^2.0.4",
    "laravel-mix": "^2.1.11",
    "load-google-maps-api": "^1.2.0",
    "lodash": "^4.17.10",
    "masonry-layout": "^4.2.2",
    "perfect-scrollbar": "^1.1.0",
    "popper.js": "^1.14.3",
    "skycons": "^1.0.0",
    "vue": "^2.5.16"
  }

and in my blade footer script:

@section('footer')
    <script type="text/javascript">
        if (typeof jQuery != 'undefined') { alert(jQuery.fn.jquery); }

        $(function() {
        $('#cc-number').validateCreditCard(function(result) {
            $('.log').html('Card type: ' + (result.card_type == null ? '-' : result.card_type.name)
                + '<br>Valid: ' + result.valid
                + '<br>Length valid: ' + result.length_valid
                + '<br>Luhn valid: ' + result.luhn_valid);
        });
        });
    </script>
@endsection

after i run npm run dev and load my page, i receive error:

Uncaught ReferenceError: $ is not defined

and my alert(jQuery.fn.jquery); is not triggered

how do i load jquery from npm so then i can use it at inline html code in blade?

like image 391
AnD Avatar asked Jul 30 '18 14:07

AnD


2 Answers

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

like image 59
Ahmed Aboud Avatar answered Oct 13 '22 17:10

Ahmed Aboud


Try this in your main.js file

global.$ = global.jQuery = require('jquery');
like image 26
Odyssee Avatar answered Oct 13 '22 17:10

Odyssee