We as Magento 2 store developers often come across a requirement where we have to customise a specific Javascript file from a module. How do we go about it?. Today we will share the two methods using which one can customize a javascript file in Magento 2. The first one is to override the Javascript file using your own custom module which we have already covered in a previous blog. Today we will show you how you can override a Javascript file in Custom theme Magento 2. It is one of the easiest ways to override a Javascript file in Magento 2. The key idea is to create the Javascript file structure in the your custom theme using the same path structure as you have it for custom or Magento module. Let us suppose we want to customize the remarketing.js file present in one of our modules called GoogleTagManagerPro in the vendor folder. Follow the steps below to override this JS file. 

Step 1:- Find the path structure where this file is present as well as the name of the module. Our module is present in the path vendor/scommerce/googletagmanagerpro/view/frontend/web/js . For the module name we will check the module.xml file present in the etc folder. The module name is Scommerce_GoogleTagManagerPro.

Override a javascript file in custom theme Magento 2

Step 2:- Next, we will create the module directory in the app/design/frontend/vendor/theme folder. Go to the path app/design/frontend/custom/theme and create a folder named “Scommerce_GoogleTagManagerPro”.

Step 3:-  Now create the javascript file structure based on the core principles. Create the following directory as in the original module app/design/frontend/custom/theme/Scommerce_GoogleTagManagerPro/view/web/js. In short we need to create view, web, and js folders as shown below.

Override a javascript file in custom theme Magento 2

Step 4:- Copy the remarketing.js file in this folder and perform your customizations. 

Step 5:- We want Magento to pick our customized file instead of the original javascript file. For that we will deploy the static content and flush the cache. Run the below commands on your server to see the changes:-

php bin/magento setup:static-content:deploy
php bin/magento c:f

We learnt that in Magento 2 a javascript file can be overridden in the custom theme. We hope that this guide was useful for you in your development ventures.

Similar Posts