How To Add Custom JS File In Magento 2 With requireJS?

0
50
customeJs magento2

This topic discusses how to add custom js File with the components provided by Magento or custom replacement implementations.

We strongly recommend that you do not change the source code of default Magento components and widgets. All customizations must be implemented in custom modules or themes.

To add a custom JS component (module), take the following steps:

Step1: Add custom js file in require js

To add js file in your magento 2 custom module, you need to add “requirejs-config.js” file in your module with path “app/code/magentoshare/Test/view/frontend”.

requireJs

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.
Magentoshare_Test/js/wkrequirejs‘ is your file path with file name which is present at path:
“app/code/Magentoshare/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 add your require js content in file:
“pub/static/_requirejs/frontend/Magento/luma/en_US/requirejs-config.js”

Step2: call and use the file:

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

call file custom js

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.
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.

Whenever your this code get executed then, it read 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.

Step3: use data passed in when calling requirejs in .phtml file:

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

requireJs

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>“.

Result:  the div element is removed from your page.