Laravel Mix my javascript code is not running
Asked Answered
B

1

6

I'm using Laravel facing a problem when compiling assets. By default laravel provides a wrapper around webpack which is laravel-mix, laravel-mix using file called webpack.mix.js, and by using npm run dev command, laravel-mixcompile all js files into one webpack bundle js file.

Code of webpack.mix.js:

let mix = require('laravel-mix');

mix.js('resources/assets/js/app.js', 'public/js')
   .sass('resources/assets/sass/app.scss', 'public/css');

I have a Main.js file which has some jquery code.

Main.js:

;( function( $, window, document, undefined ) {

    'use strict';
    $(window).on('load', function() {
        alert('ready');
    });
 }
)( jQuery, window, document );

My directory structure is something like this

resources\assets\js

app.js
bootstrap.js
Main.js

Code of app.js:

require('./bootstrap');

Code of bootstrap.js:

try {
    window.$ = window.jQuery = require('jquery');// jquery
    require('bootstrap');// bootstrap framework js
    require('./Main'); // Main.js


} catch (e) {
}

When i type command npm run dev all assets are compile into one file then why my Main.js jquery code which is just an alert popup doesn't execute on the page.

But when i change order of the bootstrap.js file into something like this then my Main.js code is execute.

try {
    window.$ = window.jQuery = require('jquery');// jquery
    require('./Main'); // Main.js
    require('bootstrap');// bootstrap framework js



} catch (e) {
}

Why this thing is happening. Does conflict happen between bootstrap framework js file and Main.js file.

Bernie answered 23/11, 2017 at 13:17 Comment(2)
Can you provide your browser console when your code doesn't execute?Waterresistant
@Waterresistant There is not any error comes, but when i load my page my Main.js script is not executedBernie
A
7

Replying to the tldr in the comments:

There is not any error comes, but when i load my page my Main.js script is not executed

I had this same issue and including the manifest.js and vendor.js solved these issues:

<script src="{{ mix('js/manifest.js') }}"></script>
<script src="{{ mix('js/vendor.js') }}"></script>
Adallard answered 3/5, 2021 at 17:39 Comment(2)
Thank you! Tried to solve a similar problem for 2 hours. Now it is fixed. Did not know that .extract() is applied to every js you compile with mix!Escapement
Yes it is applied to every js file. It looks at all the dependencies of all included js files and then determines what should be included in the vendor.js. And the 'start script' (the one that calls the bundled JavaScript files that are created from the entrypoints) is the manifest.js, so it should be included as well.Adallard

© 2022 - 2024 — McMap. All rights reserved.