How to load custom module js file in magento 2?
-
13-12-2019 - |
Question
I have created banner slider module for magento 2. I have called JS file using following ways and its working fine. In block class I created following function
public function getBaseJs($fileName){
return $this->_storeManager->getStore()->getBaseUrl(
\Magento\Framework\UrlInterface::URL_TYPE_MEDIA
).'bannerslider/js/'.$fileName;
}
and this function is called in bannerslider.phtml
file as following manner.
<script type="text/javascript" src="<?php echo $this->getBaseJs('jquery-1.7.min.js') ?>"></script>
<script type="text/javascript" src="<?php echo $this->getBaseJs('jquery.flexslider.js') ?>"></script>
But, according to jQuery dependency mechanism of
require.js
How I can do it ?
Solution
Finally, I got the solution for my query. I would like to share it in details as below.
Step 1: Add your module js file under <Vendor>/<Module_Name>/view/<area>/web/js/
e.g. <Vendor>/<Module_Name>/view/<area>/web/js/flexslider.js
Step 2: Create requirejs-config.js
file under <Vendor>/<Module_Name>/view/<area>/
e.g. <Vendor>/<Module_Name>/view/<frontend>/requirejs-config.js
Add following code to requirejs-config.js
var config = {
map: {
'*': {
bannerslider: 'VendorName_ModuleName/js/flexslider'
}
}
};
Note: you may set your object name as per your choice. In my case I have set as bannerslider
and do not add the .js extension to file name in VendorName_ModuleName/js/flexslider
Step 3: Call the function
of your module js in .phtml
file as following manner.
<script type="text/javascript">
require(['jquery','bannerslider'],function($){
$(window).load(function() {
$('.flexslider-8').flexslider({
animation: "fade",
controlNav: "thumbnails",
slideshowSpeed: 2000,
minItems: 2,
maxItems: 4
});
});
});
</script>
Its working fine for me.
Trace : Use Net
tab to see requested URL of js file loaded or not.
OTHER TIPS
My way is:
Step 1
Include an extension's base javascript file using layout instructions.
Step 2
Require the extension's other javascript files from the base file with RequireJS:
require(
[
'jquery',
'{VendorName}_{ModuleName}{path_to_js_file/relative_to/view/web/no_js_at_end}'
// ex. Magento/Ui/view/base/web/js/grid/sticky/sticky.js
// became Magento_Ui/js/grid/sticky/stick
],
function($, someOtherLibrary) {
// custom code here...
);
});