Magento 2 RequireJS

Magento 2 makes use of RequireJS, which is a JavaScript module loader and thus eliminates the need to add your JavaScript files in a particular order.

In Magento 1, adding JavaScript files in a particular order could prove tricky. An example of this is needing to add a jQuery plugin JavaScript file after firstly adding the jQuery library. Within Magento 1’s RWD theme, as Magento included jQuery by default, developers needed to ensure their plugins loaded after Magento had loaded jQuery via layout XML.

Please note that although you do not have to add JavaScript using RequireJS (as seen in the article), it is recommended to do so.

To demonstrate RequireJS in action, we’ll work off of the example frontend module provided in this article.

To start with, add a requirejs-config.js file within the view/frontend directory of your module’s directory structure. If you have an adminhtml module, then you would need to add the config file to view/adminhtml.

Within this configuration file, map your JavaScript module to a path. In the below example, the custom module is mapped to the js/custom.js file within your module’s web directory.

// app/code/[Vendor]/[Module]/view/frontend/requirejs-config.js

var config = {
    map: {
        "*": {
            custom: "[Vendor]_[Module]/js/custom"
        }

    }
};

Essentially we’re giving our JavaScript module an alias of custom. You may notice that the .js extension is missing. This is because RequireJSwill automatically add it.

Now we need to go ahead and create the custom.js file. For simplicity, a string will be returned as part of the message property.

// app/code/[Vendor]/[Module]/view/web/js/custom.js

define([],function(){
    return {
        'message':'Some example text'
    };
});

A template file is needed to output the message. Usually a template is included via layout XML that simply includes the JavaScript.

Once you’ve configured this template within the layout file to render this template, we can write the following.

// app/code/[Vendor]_[Module]/view/templates/js.phtml

<script type="text/javascript">
    require(['custom'],function(example){
        alert(custom.message);
    });
</script>

This will provide you with an alert box when the page loads.

We may wish to include popular jQuery plugins, such as a slider library. Assuming that you’ve already got the JavaScript library downloaded and added to your module’s js directory, configure the following within your module’s requirejs-config.js file.

// app/code/[Vendor]/[Module]/view/frontend/requirejs-config.js

var config = {
    map: {
        '*': {
            flexslider: '[Vendor]_[Module]/js/jquery.flexslider-min'
        }
    },
    shim: {
        flexslider: {
            deps: ['jquery']
        }
    }
};

Here the jquery library is added as a dependency, as FlexSlider depends on jQuery being available.

Then, within the template file, assuming you have set up your FlexSlider HTML markup, you can initialise the FlexSlider using .flexslider().

// app/code/[Vendor]_[Module]/view/frontend/templates/js.phtml

<script type="text/javascript">
    require(['flexslider'],function($, flexslider){
        $(document).ready(function () {
            $('.flexslider').flexslider();
        });
    });
</script>

Note: This article is based on Magento CE version 2.1.