Magento 2 add custom js file in module

create category custom layout in Magento 2

Hey reader today we will disscuss about to add js file in custom module .

Please follow below step to done this job.

Step 1. Create requirejs-config.js file on below path :-

app/code/VendorName/ModuleName/view/frontend/requirejs-config.js

var config = {
    map: {
        '*': {
            myjs: 'VendorName_ModuleName/js/myjs',
        }
    },  
    deps: ['jquery']
};

Step 2. Create myjs.js file on below path:-

app/code/VendorName/ModuleName/view/frontend/web/js/myjs.js

define(['jquery','jquery/ui'], function($, alert) {
    "use strict";
    $.widget('myjs.vendorname', {

        _create: function() {
        var roofing = this.options.myProducts;
        -----
        -----
        },
    });

    return $.myjs.vendorname;
});

Step 3. Add/call js file in phtml file.

Create tempalate file index.phtml file on below path:-

app/code/VendorName/ModuleName/view/frontend/templates/index.phtml


<script type="text/x-magento-init">
{
"body" :
{
"VendorName_ModuleName/js/myjs": {
"myProducts":'test'
}
}
}
</script>

Step 4. Run upgrade and deploy commands

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy -f 

Check myjs.js file network tab in browser


Related Post on Setup Multi Website In Magento 2

Like us on Facebook and Linkedin for more updates.

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top