I have been investigating how various module concepts can be applied within NodeJS and browser applications using the the NodeJS require (obviously in NodeJS apps) and RequireJS for the web browser environment.
It then dawned on me that some modules may be useful for use by both the client and server applications and thus could be reused.
How can modules be developed so that they are compatible with both of these environments?
One is synchronous and one asynchronous. My first thought was to utilise the asynchronous syntax and then to define a custom module for NodeJS which simply invokes the asynchronous callback, synchronously. But how would the RequireJS-emulator be included into the cross-environment module without first using the NodeJS synchronous callback?
See this post : Bridging the module gap between Node.js and browsers
See also the set of boilerplates at https://github.com/umdjs/umd
About async vs. sync -- for define() in Node, it is common to just use synchronous execution of the factory function passed to define. That is how requirejs works when running in Node.
The http://uRequire.org project bridges the gaps of the AMD & nodejs / commonJs formats. U can write in either (or both), and execute / deploy to any of the two or a standalone.js
.
check this resource here: it's Not Hard: Making Your Library Support AMD and CommonJS it explains everything very well
I will post the take-away code you need
, but to understand
everything you should read that article
by this code, you added AMD(requireJs) and Node support for your js library
(function (global, factory) {
if (typeof define === 'function' && define.amd)
define(['jQuery'], function ($) {
return (global['toaster'] = factory($))
});
else if (typeof module === "object" && module && typeof module.exports === "object")
module.exports = (global['toaster'] = factory(require('jquery')));
else global['toaster'] = factory(global['jQuery']);
})(this, function ($) {
// implementation goes here
var myModule = {};
return myModule;
function helper() {
}
})
one more thing, I found out this Universal Module Definition GitHub project for all variant implementations you can check them all