I have created a custom module and now need to add custom js file into that module. I have read many post about this but not having a clear answer.
Can anyone please help me with this?
I have created a custom module and now need to add custom js file into that module. I have read many post about this but not having a clear answer.
Can anyone please help me with this?
Firstly you have to create a requirejs-config.js file in dir Vendor/Module/view/frontend to include your custom js file. I am taking an example of owlCaraulsel js.
var config = {
paths: {
'owlcarousel': 'Vendor_Module/js/jquery/owl.carousel.min'
},
shim: {
'owlcarousel': {
'deps': ['jquery']
}
}
};
Now add your js file in dir of the module if its for frontend i.e.
Vendor/Module/view/frontend/web/js/jquery/owl.carousel.min.js
Now you call this in you phtml file:
<script type="text/javascript">
requirejs(['jquery','owlcarousel'], function(jQuery, owlcarousel) {
...
});
</script>
Add a custom JS component
To add a custom JS component (module), take the following steps:
Replace a default JS component
To use a custom implementation of an existing Magento JS component: Place the custom component source file in one of the following locations:
Create a RequireJS configuration file requirejs-config.js, having specified the following:
var config = {
"map": {
"*": {
"<default_component>": "<custom_component>"
}
}
};
<default_component>:
the name of the default component you replace<custom_component>:
the name of the custom componentFor example, if you want to use custom navigation-menu.js script instead of the default menu widgets, your requirejs-config.js should contain the following:
var config = {
"map": {
"*": {
"menu": "js/navigation-menu",
"mage/backend/menu": "js/navigation-menu"
}
}
};
Place your requirejs-config.js file in one of the following directories (according to the location of your custom script, see step 1 of this procedure):
This way your custom JS component is used instead of the Magento component in all entries all over the frontend area.
Extend a default JS component
You can add a custom JS component/widget, which will extend a default Magento component/widget.
Extend Magento widget:
To extend a default Magento jQuery widget, create .js with the following contents:
define([
'jquery',
'jquery/ui',
'mage/<widget.name>' // usually widget can be found in /lib/web/mage dir
], function($){
$.widget('<your_namespace>.<your_widget_name>', $.mage.<widget.name>, { ... });
return $.<your_namespace>.<your_widget_name>;
});
Where the following notation is used:
<your_namespace>.<your_widget_name>
- the name of your custom widget. According to the jQuery widgets naming convention, must contain a namespace and name.mage.<widget.name>
- the name of the Magento widget that you extend.Reference: https://devdocs.magento.com/guides/v2.3/javascript-dev-guide/javascript/custom_js.html
I hope this will help