alex32's avatar
Level 2

jQuery import as a module

I'm trying to import a jQuery script into another one, as a module I get no errors but the script wont execute. main.js and apphelp.js are working fine when merged into a single file.

Can you please help. Many thanks

  • jQuery: 3.5
  • Laravel 11

main.js

export function exmain () {

	'use strict'; 
     var a= "hello main";
     alert (a);

    function one() {
        //..
    }
    
}


apphelp.js

export function exhelp () {
    'use strict'; 
    var msg='hello module';
    
    function two() {
        //..
    }
     

    $('.toast-msg').text('msg'); 
}


loader.js

import {exmain} from './main.js'
import {exhelp} from './apphelp.js'


(function ($) {
  
  exmain();
  exhelp();

})(jQuery);


package.json

{
    "private": true,
    "type": "module", 
    ...
}    


main.blade.php

    ...
    <x-slot name="footer">
        @include ("main-footer")
        <script src="asset/js/loader.js" type="module"></script> 
    </x-slot> 

0 likes
4 replies
rodrigo.pedra's avatar

Try passing the jQuery object as a parameter to the other modules:

export function exmain ($) {
	'use strict'; 

     var a= "hello main";
     alert (a);

    function one() {
        //..
    }
    
}
export function exhelp ($) {
    'use strict'; 
    var msg='hello module';
    
    function two() {
        //..
    }
     

    $('.toast-msg').text('msg'); 
}
import {exmain} from './main.js'
import {exhelp} from './apphelp.js'


(function ($) {
  
  exmain($);
  exhelp($);

})(jQuery);
alex32's avatar
Level 2

Thanks Rodrigo, I think I found the issue. Passing $ as a parameter didn't change anything. But I removed the following line under laravel-plugin [2]

vite.config.js:

'resources/css/app.css', 

Then, I imported all .css from app.js, including my own scripts. It looks that by importing this way I also got rid of the JS error which was preventing my own scripts to be bundled. I still have a problem [1] of bundling all JS files into one, but at least the current bundle is working. Many thanks

[1] The open issue of bundling all JS files with Vite: https://laracasts.com/discuss/channels/vite/vite-jquery-is-not-a-function

[2] https://laravel.com/docs/11.x/vite#main-content

1 like
rodrigo.pedra's avatar

@alex32 I didn't know you were using Vite.

When using Vite, specially with the Laravel plugin, use the @vite() blade helper to import the compiled files. Otherwise, your server won't know how to look for the files correctly.

See: https://laravel.com/docs/11.x/vite#loading-your-scripts-and-styles

If you create a public/assets/js directory, and add the files you described there, your previous attempt should work.

Now that is clearer what setup you are using, there is no way your server could resolve the assets/js/loader.js if this was placed out of the public directory.

Please or to participate in this conversation.