How to include and use custom js file with require js in magento2

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 custom js file in require js file:

To add 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 in 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 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.

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 our 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 serialize 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 your this code get executed then, it reads the “wktestrequire” under <script> tag.
then it includes the file, which is aliased with the alias name: “wktestrequire”, i.e. your js file is got included in your .phtml file, and then in your js you can use the data, which is passed 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 passed in .phtml and the options which are defined in the js file by using “self.options.<parameter name>“.

And now the div element is removed from your page.

I hope, this blog will help you to use the js and require js file in Magento2.

. . .

Comments (2)

Add Your Comment

  • Rafael Corrêa Gomes ♛
    Thanks for sharing!
    • Webkul Support
      You are most welcome.
  • css.php
    Hire Us!
    Brief us about your requirements and we'll get back to you.
    Woo! Hooy!
    We have just recieved your project brief and our expert will contact you shortly.
    Send Again
    Close