Today we will see how we can manage our JavaScript files using RequireJS in Magento2.
To learn more about RequireJS, please check this post.
- Make sure you have created your module and theme directories.
- Create a new file named requirejs-config.js under the directory structure:
app/design/frontend/Mycompany/Basic/requirejs-config.js
Here Vendor = Mycompany, Theme name = Basic
- Add lines similar to this:
var config = { map: { '*': { flexslider: 'Mymodule_Test/js/jquery.flexslider-min', header: 'Mymodule_Test/js/store/header' } } };
In the above file, we have mapped names for file locations.
Here I assume that you have created a module named Mymodule/Test.
Also, you have jquery.flexslider-min.js and store/header.js under Mymodule/Test/view/frontend/web/js folder. - Lastly, remove the existing requirejs file from this location:
pub/static/_requirejs/frontend/Mycompany/Basic/en_US/requirejs-config.js
It will be generated automatically again on page reload.
- Now, in any of your template files, write script tag like this:
<script type="text/javascript"> require(['jquery', 'flexslider'],function($){ (function() { $('.flexslider').flexslider(); })(jQuery); }); </script>
Why requirejs-config.js file written inside app/design/frontend folder rather than app/code module folder?? Please advise.
Excellent documentation!!!!
Finally my js issue solved, Thank you very much, I was struggling with one js library to load and followed so-many articles nothing helped exactly, but your two documentations “Module creation” and “Js loading through RequireJs” really helped me.
And one question, is any way to load js libraries without modules? I mean help of theme.
Again, Thanks for your effort!