Extending / Overriding JS in Magento 2

Hello everyone. Sometimes, you want to change the Magento JS core. But you can not change directly in Magento source code. So you must override the Magento JS. In this blog, I will show you how to override the Magento JS core and replace it by your custom JavaScript.

The structure

In [Namespace]/[Module]/view/frontend/requirejs-config.js add this

var config = {
    map: {
        '*': {
            'Magento_Customer/js/action/check-email-availability':'Techhalls_Shipping/js/action/check-email-availability'
        }
    }
};

The structure requirejs-config.js is

var config = {
  "map": {
    "*": {
      "<default_component>": "<custom_component>"
    }
  }
};

After that we need to create customer js file [Namespace]/[Module]/view/frontend/web/js/action/check-email-availability.js

The example for custom js:

/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
define(
    [
        'jquery',
        'mage/storage',
        'Magento_Checkout/js/model/url-builder'
    ],
    function ($, storage, urlBuilder) {
        'use strict';

        return function (deferred, email) {
            return storage.post(
                urlBuilder.createUrl('/customers/isEmailAvailable', {}),
                JSON.stringify({
                    customerEmail: email
                }),
                false
            ).done(
                function (isEmailAvailable) {
                    if (isEmailAvailable) {
                        deferred.resolve();
                    } else {
                        deferred.reject();
                        $('.captcha-reload').trigger('click');
                    }
                }
            ).fail(
                function () {
                    deferred.reject();
                }
            );
        };
    }
);