Magento 2 | Add custom .js file.

February 11th, 2019

For an optimization project, i need to modify a Magento 2 theme that isn’t developed by me.
In this case, i prefer touch minor code as possibile, because , from one way, i don’t know all custom code that was added, and in the other, i want that the debug can be done in a very simple way.

Ok, first thing to do is connect by FTP client or SSH, to the custom theme that our store is using.
Check if the theme have on his root folder a folder called “web”, if so, all is right, otherwise you must create it.
Inside the “web” folder, check if have a folder called “js”, if so, all is right, otherwise you must create it.

Now we must have a structure like this one “/app/design/frontend/theme-vendor/theme-name/web/js”.
Next step is to create your custom js file, you can named it as you like (es: custom-theme.js ), important is that the file is placed inside the “/web/js/” folder taht is in the root of the custom theme.

Now we need to “register” the file, so open ( or create if you can’t find one.. ) the file ” requirejs-config.js “.
Inside this file you have a section called “deps”, is the section where you can add you custom files.
Modify this section adding this snippets:

"js/custom-mp",

your final file “requirejs-config.js” it must look like mine:

var config = {

    deps: [
        "js/custom-theme",
    ]
};

You can notate that the js file is called without the extension “.js”.

Last thing to do is add some code to our custom js.
Open it and add:

define([
    "jquery",
  ], 
  function($) {
    "use strict";
  
      $(document).ready(function($){
        console.log('All right Sparky!!');
      });
      return;
  });

Basically, define that is dependent from jQuery and inside on a Document Ready Function, we add a “Console log”.

Save’s file, Clear Cache, Flush Cache and reindex all, and reload shop page:

You can see that your console.log is correctly printed in the browser console.

That’s all from now you can add custom js or js library without problems.