I've created a node module that is essentially just some useful JS that can also be used client side. I know that require.js can load common.js components, but I don't necessarily want to make a mandate that everyone who uses my module client side also needs require or common.js or something. I also don't want to force them to remove the module.exports = ...
at the bottom of the file. How do others solve this problem? Do you just create 2 versions, or 2 "compiled" versions rather? Does module.exports work everywhere?
This is what underscore.js does:
if (typeof exports !== 'undefined') {
if (typeof module !== 'undefined' && module.exports) {
exports = module.exports = _;
}
exports._ = _;
} else {
root['_'] = _;
}
This has worked for me (CoffeeScript). Assume 'Namespace' is what you want to claim on the window
scope for the client
(module ? {}).exports = @Namespace =
my: 'cool'
module: '!'
Then you can use require('namespace').my === 'cool'
in Node.js or Namespace.my === 'cool'
in the browser. This translates into JS as
(typeof module !== "undefined" && module !== null ? module : {}).exports = this.Namespace = {
my: 'cool',
module: '!'
};