You can easily use your library in Node.js and client side (aka Isomorphic). All that is needed is a couple of conditional statements and an encapsulating IIFE.
(function (root) {
}(this));
The IIFE calls itself using this to reference the global context. Client side "this" will reference "window". In Node.s it will reference the "module" parameter.
Now we can check to see if the "exports" object exists. If it does then check if module.exports exists. In node, imagine this line is inserted at the top of every module: var exports = module.exports = {}
. module.exports
is then returned to the require function. We need to make sure that both exports and module.exports are pointing to the same object.
If the script is run client side, then exports
should not exist, so we just add our awesome library to the global namespace, referenced by root
.
if (typeof exports !== "undefined") {
if (typeof module !== "undefined" && module.exports) {
module.exports = myAwesomeLibrary;
}
exports = myAwesomeLibrary;
} else {
root.myAwesomeLibrary = myAwesomeLibrary;
}
All together then
(function (root) {
var myAwesomeLibrary = {};
if (typeof exports !== "undefined") {
if (typeof module !== "undefined" && module.exports) {
module.exports = myAwesomeLibrary;
}
exports = myAwesomeLibrary;
} else {
root.myAwesomeLibrary = myAwesomeLibrary;
}
//rest of your library ...
}(this));