How to add custom JavaScript and mixins in Magento 2 with requireJS?

How to add custom JavaScript and mixins in Magento 2 with RequireJS – Today we will see how to add custom javascript file and a mixin file to same RequireJS file in custom module. I recently faced a practical issue to add a javascript and a mixin file to RequireJs file to one of my custom checkout module.

We can simply add an external file to RequireJs file like below.

var config = {
    map: {
        '*': {
            'fileupload': 'Ayakil_CheckoutCustomField/js/fileupload'
        }
    }
};

And also we can add a mixin file like below.

var config = {
   config: {
        mixins: {
            'Magento_Checkout/js/action/set-shipping-information': {
                'Ayakil_CheckoutCustomField/js/action/set-shipping-information-mixin': true
            }
        }
    }
};

Here is the sample module directory structure which contains custom javascript file and mixin file.

how to add require js in magento 2
Sample Module structure.


But i want to add both JavaScript file and mixin to one RequiJs file. So we can add both in requirejs-config.js file like below.

var config = {
    map: {
        '*': {
            'fileupload': 'Ayakil_CheckoutCustomField/js/fileupload'
        }
    },
    config: {
        mixins: {
            'Magento_Checkout/js/action/set-shipping-information': {
                'Ayakil_CheckoutCustomField/js/action/set-shipping-information-mixin': true
            }
        }
    }
};

Like this we can add javascript file and mixin file in requirejs-config.js file. Hope this will help you in your magento custom development.

You can read more interesting articles on create graphql module in magento 2.

Read and share your thought + share this article too 🙂 .

Leave a Reply

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