How to add JS to M2

Published on 21 May 2019

Source

To load a custom main.js file on all pages (in the RequireJS-way) this is a good way:

1) Create main.js

Create main.js within the theme folder

<theme_dir>/web/js/main.js

with this content:

define([
  "jquery"
], 
function($) {
  "use strict";

  // Here your custom code...
  console.log('Hola');

});

In short: we declare dependencies at the start, e.g. "jquery". We define as function’s parameter the variable name for using the dependency within the function, e.g. "jquery" --> $. We put all our custom code within function($) { ... }.

2) Declare main.js with a requirejs-config.js file

Create a requirejs-config.js file within the theme folder:

<theme_dir>/requirejs-config.js

with this content:

var config = {

  // When load 'requirejs' always load the following files also
  deps: [
    "js/main"
  ]

};

"js/main" is the path to our custom main.js. The “.js” extension is not required.

Our requirejs-config.js will be merged with other requirejs-config.js defined in Magento.

RequireJS will load our main.js file, on each page, resolving dependencies and loading files in an async way.


Optional: Including third-party library

This is the way to include third-party libraries.

1) Add the library in web/js:

<theme_dir>/web/js/vendor/jquery/slick.min.js

2) Open requirejs-config.js and add this content:

var config = {

  deps: [
    "js/main"
  ],

  // Paths defines associations from library name (used to include the library,
  // for example when using "define") and the library file path.
  paths: {
    'slick': 'js/vendor/jquery/slick.min',
  },

  // Shim: when you're loading your dependencies, requirejs loads them all
  // concurrently. You need to set up a shim to tell requirejs that the library
  // (e.g. a jQuery plugin) depends on another already being loaded (e.g. depends
  // on jQuery).
  // Exports: if the library is not AMD aware, you need to tell requirejs what 
  // to look for so it knows the script has loaded correctly. You can do this with an 
  // "exports" entry in your shim. The value must be a variable defined within
  // the library.
  shim: {
    'slick': {
      deps: ['jquery'],
      exports: 'jQuery.fn.slick',
    }
  }

};

It looks more complicated than what it actually is.

3) Add the dependency within main.js:

define([
  'jquery',
  'slick'
], 
function($) {

  // ...

});

Development

Everything web development related, rants, snippets, tutorials, quests; it’s all there.

All categories

All tags

All posts