I recently searched a lot on use of non-amd jquery code with requirejs but couldn't find a proper way to do it.
To be more specific, I want to use pana-accordion.js found at below mentioned url.
But the problem is that it is not amd aware and nor it exports anything out of it.I am currently doing it for magento-2 cms.So far I have created my custom.phtml
and called it on homepage through admin area.Below is my custom.phtml
<div class="pana-accordion" id="accordion">
<div class="pana-accordion-wrap">
<div class="pana-accordion-item" style="background-color: #F44336"><img width="500" height="300" src="https://unsplash.it/500/300?image=57" /></div>
<div class="pana-accordion-item" style="background-color: #2196F3"><img width="500" height="300" src="https://unsplash.it/500/300?image=49" /></div>
<div class="pana-accordion-item" style="background-color: #4CAF50"><img width="500" height="300" src="https://unsplash.it/500/300?image=39" /></div>
<div class="pana-accordion-item" style="background-color: #FF9800"><img width="500" height="300" src="https://unsplash.it/500/300?image=29" /></div>
</div>
</div>
<script type="text/javascript">
require(['jquery','panaaccordion'],function($, accordion) {
accordion.init({
id: 'accordion',
});
})
</script>
And Here is configuration for pana-accordion.js
javascript module in requirejs-config.js
var config = {
'map': {
'*': {
'panaaccordion': 'js/pana-accordion'
}
},
'shim': {
'panaaccordion': {
deps: ['jquery'],
exports: 'accordion'
}
}
}
Below is some code lines for pana-acordion plugin
var accordion= {
init: function(options){
var that=this;
options = $.extend(true,{
expandWidth: 500,
itemWidth: 100,
extpand: 0,
autoPlay: true,
delay: 3000,
animateTime: 400,
borderWidth: 1,
autoPlay: true,
deviator: 30,
bounce:"-50px"
},options);
.....
As you can see, it doesn't wrap code inside define()
nor it exports or return anything.Rather accordion object is declared globally.
So far I have following questions (those marked as bold sorry for bad formatting but I am trying to improve it).
If I wrap the code inside define like below,
define(['jquery'],function($){
//pana-accordion plugin code
});
Still, there is an error in console that says Uncaught TypeError: Cannot read property 'init' of undefined
, even though I created exports entry in shim configuration. But error resolves when I finally write return statement after accordion object.
return accordion;
What is the purpose of using shim, if we have to manually write return statement from plugin for object for example?
Second, Do I have to write whole path for shim configuration? If I map alias panaaccordion
for file located at 'js/pana-accordion'
, still I have to use 'js/pana-accordion'
for shim configuration otherwise there are some loading order issues.
Third- Can I use such non-amd plugins with requirejs without modifying a single line from them?? If yes, How?
from Use of non-amd jquery plugins with requirejs without modifying them?
No comments:
Post a Comment