Menu Close

    How to Use Require JS in Magento 2

    In this article, we will learn about RequireJS in Magento 2. But what is require js and how to use it in default, for this you can check out our blog: What is RequireJs

    Now to explain it in Magento 2, I am taking an example.

    How to add a Custom JS file in Require js file

    To add a js file in your Magento 2 custom module, you need to add “requirejs-config.js” file in your module at path “app/code/Webkul/Test/view/frontend”.

    var config = {
        map: {
            '*': {
                wktestrequire: 'Webkul_Test/js/wkrequirejs',
            }
        }
    };

    In this :
    by the map, it maps your file with the alias name which you defined in the object.
    ‘*’ used to define that you are using a new module to use require js, if you want to add it to the existing one then you need to write the module name.
    wktestrequire‘ is an alias name to alias your file.
    Webkul_Test/js/wkrequirejs‘ is your file path with the file name which is present at path:
    “app/code/Webkul/Test/view/frontend/web/js/wkrequirejs.js”

    extension of the file is not needed, it takes js as a default type.

    Searching for an experienced
    Magento 2 Company ?
    Read More

    By this file it adds your require js content in file:
    “pub/static/_requirejs/frontend/Magento/luma/en_US/requirejs-config.js”

    How to call and use the file:

    Now we call the above file in our .phtml file to perform some operations.
    I create a file at path:
    “app/code/Webkul/Test/view/frontend/templates/test.phtml”

    <div id="testdiv">
    	<a>Test anchor tag</a>
    </div>
    
    <?php
    $formData = [
        'divElement'       =>  '#testdiv',
    ];
    $serializedFormData = $this->helper('Magento\Framework\Json\Helper\Data')->jsonEncode($formData);
    ?>
    <script type="text/x-magento-init">
        {
            "*": {
                "wktestrequire": <?php /* @noEscape */ echo $serializedFormData; ?>
            }
        }
    </script>

    In this code, i took a div element, and in the formData array, i define that element’s id with “devElement“.
    and then i encoded that data to send the data in serialized format.
    Now, i took a script tag, in this i used same alias name which i used in my “requirejs-config.js” file and passes my serialized data with that js alias name.

    Now, whenever this code gets executed then, it reads the “wktestrequire” under <script> tag.
    Then it includes the file, with the alias name: “wktestrequire”, i.e. your js file includes in your .phtml file, and then in your js you can use the data, which is passes in this file.

    How to use data passed in when calling requirejs in .phtml file:

    Now I created a file with name “wkrequirejs.js” at:
    “app/code/Webkul/Test/view/frontend/web/js”

    define([
        "jquery",
        'Magento_Ui/js/modal/alert',
        "jquery/ui",
    ], function ($, alert) {
        'use strict';
        $.widget('mage.wktestrequire', {
            options: {
                confirmMsg: ('divElement is removed.')
            },
            _create: function () {
                var self = this;
                $(self.options.divElement).remove();
                alert({
                    content: self.options.confirmMsg
                });
            }
        });
        return $.mage.wktestrequire;
    });

    Here,

    In define, I includes some magento js files and alias them in function parameter.

    options“, is an object in which we can define the variable, which will be in use in this file.
    _create function is executed when this file get executed.
    You can access the parameters that are pass in .phtml and the options which are defined in the js file by using “self.options.<parameter name>”.

    And now the div element is clear from your page.

    I hope, the RequireJS Magento 2 blog will help you to use the js and require js files in Magento 2. For more information or queries, please create a ticket or send an email.

    . . .
    Discuss on Helpdesk

    Leave a Comment

    Your email address will not be published. Required fields are marked*


    2 comments

  • Rafael Corrêa Gomes ♛
    Thanks for sharing!
    • Webkul Support
      You are most welcome.
  • Back to Top