Overide core javascript in magento
Override core Javascript files in Magento 2

Today we are going to talk about how to Override core Javascript files in Magento 2 in your own custom module.

We had a requirement to add custom attribute to checkout which we are not covering in this post but we will talk about how to override Magento_Checkout/js/model/shipping-save-processor/default Magento 2 core Javascript file in your own custom module. The similar way you can override any of the Magento 2 core Javascript file.

Let’s get started to override core javascript in Magento 2-:

Step 1: Create requirejs-config.js under ScommerceCustomviewfrontend folder with the following code

/** * Copyright © 2015 Scommerce Mage. All rights reserved. * See COPYING.txt for license details. */ var config = { map: { '*': { "Magento_Checkout/js/model/shipping-save-processor/default" : "Scommerce_Custom/js/shipping-save-processor-default-override" } }
};

Step 2: Add shipping-save-processor-default-override.js file under ScommerceCustomviewfrontendwebjs folder with following content -:

 console.log('init Scommerce/Custom/view/frontend/web/js/shipping-save-processor-default-override.js')
define( [ 'ko', 'Magento_Checkout/js/model/quote', 'Magento_Checkout/js/model/resource-url-manager', 'mage/storage', 'Magento_Checkout/js/model/payment-service', 'Magento_Checkout/js/model/payment/method-converter', 'Magento_Checkout/js/model/error-processor' ], function (ko, quote, resourceUrlManager, storage, paymentService, methodConverter, errorProcessor) { 'use strict'; return { saveShippingInformation: function() { var payload = { addressInformation: { shipping_address: quote.shippingAddress(), shipping_method_code: quote.shippingMethod().method_code, shipping_carrier_code: quote.shippingMethod().carrier_code, extension_attributes: { custom_checkout_field: jQuery('[name="custom_checkout_field"]').val() } } }; return storage.post( resourceUrlManager.getUrlForSetShippingInformation(quote), JSON.stringify(payload) ).done( function (response) { quote.setTotals(response.totals); paymentService.setPaymentMethods(methodConverter(response.payment_methods)); } ).fail( function (response) { errorProcessor.process(response); } ); } }; }
); 

Please note we have added the following lines to send extended attribute as part of saving shipping address information -:

 extension_attributes: { custom_checkout_field: jQuery('[name="custom_checkout_field"]').val()
}

Step 3: Once you have finished the above two steps then you need to make sure you run the following command for your site to pick up your overridden Javascript file instead of the original Magento 2 core Javascript file.

 bin/magento setup:static-content:deploy 

That’s it, Hope this article helped you in some way. Please leave us your comment and let us know what do you think? Thanks.

Similar Posts