Dedicated Magento 2 Blog

How to Override Core JavaScript file in Magento 2

Magento 2 provides a solid mechanism to inject the custom JavaScript file in our themes and modules. We can inject the custom JavaScript file using requires js. Many times while developing the store we need to change the little bit part of core JavaScript file to fulfil the client need. As we all know we can not change the core file. We must override the core file. In this post, we will see how to override core JavaScript file in Magento 2 using different methods.

We can Override Core Javascript file in Magento 2 using a custom theme or custom module. We will first see how to override core Javascript file in Magento 2 using a custom theme.

Override Core Javascript File Using Custom theme

Magento 2 provides an ability to create a custom theme to change the look and feel of default Magento 2 store. If you don’t know how to create a custom theme in Magento 2 then you should first create a custom theme by following this link. Themes are a good option when you want to quickly override the javascript file in Magento 2.

Suppose we have to override the checkout-data-resolve.js file. First, we have to identify from which module the JavaScript file is rendering. This file is rendering from the Checkout module.

First, Create the Magento_Checkout directory under app/design/frontend/Vendor/Theme path. After creating module directory follow the core Javascript directory structure. so create directory web/js/model Under Magento_Checkout directory and copy the file checkout-data-resolve.js from vendor/magento/module-checkout/view/frontend/web/js/model directory and paste into this directory.

In short copy the file from vendor/magento/module-checkout/view/frontend/web/js/model directory and paste it under app/design/frontend/Vendor/Theme/Magento_Checkout/web/js/model directory. The basic idea is to follow the core Javascript file structure and copy the file in our theme folder.

Override Core Javascript File Using Custom Module

Custom module is a great way to extend the functionality of Magento store. When you want particular functionality to implement for one specific store you can go with the custom theme to override the file. But if you want to reuse the code in different Magento stores then you should go with the custom module to override the core JavaScript file.

That’s it. We have seen two different way to override core JavaScript file in Magento 2. As a Magento 2 developer one should follow the second approach using a custom module to override the core JavaScript file in Magento 2.