I would like to create my modules in a way, that they can be used with and without requirejs (without require js they should just work normally, so I have to make sure they load correctly, like putting script tags in the right order).
So jQuery does it kindof like this:
// export module
if ( typeof define === "function" && define.amd ) {
define(["dep"], function(dep){
dep.fn.test = test;
return dep;
});
}
else{
dep.fn.test = test;
}
The actual module is defined as like so
var dep = function(...){...}
This definition and the export part is within an IIFE to keep everything in out of the global scope.
Generally it works well with one exception, the dependency is not available. This problem can be solved by defining the function within the define part, but this would mean defining it twice, in the define part and below in the else part.
How can I get this to work but only define the module once?
I have "plugin-like" extensions to a core dep which should all be in separate files so the main dep must be passed as a depenency
This works fine btw. but it would mean I write the code for test twice.
(function(){
// export module
if ( typeof define === "function" && define.amd ) {
define(["dep"], function(dep){
dep.fn.test = function(){...ssomething using dep...};
return dep;
});
}
else{
dep.fn.test = unction(){...ssomething using dep...};
}
})
Okay, I try another example
animate/animate.js (this is my main file)
define(function(){
...
return animate;
});
animate/modules/easing.js (this is a module file) (function(){ var ease = function(){ // using animate main function from animate.js // animate is not available here ... };
if ( typeof define === "function" && define.amd ) {
define(["animate/animate"], function(animate){
// animate is available here
...
animate.fn.ease = ease;
return animate;
});
}
else
{
// if no requirejs, animate is global
animate.fn.ease = ease;
}
});