How to Override JS File in Magento 2

It is strongly recommended not to change the source code of default Magento components including JS files. However, owing to the business requirements you are bound to go out of the way and override the default function.

Here, I have posted the code to override JS file in Magento 2. You may use this code when you want to extend the default JS file to extend a default Magento 2 feature! For example: you can also use the JS file to update total in Magento 2.

Method to Override JS File in Magento 2:

1. Create registration.php file in app\code\[Vendor]\[Namespace]\

<?php
\Magento\Framework\Component\ComponentRegistrar::register(\Magento\Framework\Component\ComponentRegistrar::MODULE, '[Vendor]_[Namespace]', __DIR__);

2. Create module.xml file in app\code\[Vendor]\[Namespace]\etc

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="[Vendor]_[Namespace]" setup_version="1.0.0"/>
</config>

3. Create requirejs-config.js file in app\code\[Vendor]\[Namespace]\view\frontend

var config = 
{
    map: 
    {
        '*': 
        {
            'Magento_Checkout/js/action/place-order':'[Vendor]_[Namespace]/js/action/place-order'
        }
    }
};

That’s all.

The developers may, require to use custom JavaScript for additional features not offered by the default Magento 2. To know how to add custom JS you can Read our Blog

Feel free to share the solution to extend Magento 2 JS file with fellow developers on social media.

Thank you.

Sanjay Jethva

Article by

Sanjay Jethva

Sanjay is the co-founder and CTO of Meetanshi with hands-on expertise with Magento since 2011. He specializes in complex development, integrations, extensions, and customizations. Sanjay is one the top 50 contributor to the Magento community and is recognized by Adobe. His passion for Magento 2 and Shopify solutions has made him a trusted source for...