A Detailed Guide on Using Mixins in Magento 2

What is Mixin?

A mixin is a class whose methods can be added to, or mixed in with another class. In the back-end, whenever there is a need for extension of the functionality or modification in data, it is done by plugin or extension.

But in JavaScript, if there is any need to modify data without overriding JavaScript file, then it is only possible by Mixins. Planning to use mixins but don't have any idea about how to do it?

The following guide will help you learn how to use mixins in Magento 2. Here are the steps to create a simple example of mixins.

Let’s assume that you have created a module.

Step 1. Create requirejs-config.js at app/code/MD/Helloworld/view/frontend/ and paste the below code:

var config = {
    config: {
        mixins: {
            'Magento_Swatches/js/swatch-renderer': {
                'MD_Helloworld/js/swatch-renderer-mixin': true
            }
        } // this is how js mixin is defined
    }
};

Here, I extend Magento_Swatches/js/swatch-renderer this js with our custom js MD_Helloworld/js/swatch-renderer-mixin.

Step 2: Create swatch-renderer-mixin.js at app/code/MD/Helloworld/view/frontend/web/js/ to extend the original function:

define(['jquery'], function ($) {
    'use strict';
    return function (SwatchRenderer) {
        $.widget('mage.SwatchRenderer', $['mage']['SwatchRenderer'], {
            _init: function () {
                console.log('Custom Swatch Renderer init function call successfully'); // you can write here your code according to your requirement this._super();
            }
        });
        return $['mage']['SwatchRenderer']; // Return flow of original action.
    };
});

And it is ready.

Now, all you need to do is, to remove static content and deploy the static content again.

If you face any problem, feel free to contact us, our experts will be glad to guide you through it.