module.exports client side
This is what underscore.js does:
if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _;} else { root['_'] = _;}
This answer relies on the fact that assignments are evaluated right to left. MyModule
is assigned to exports
first, then exports
is assigned to module.exports
.
If module
is not declared, an exception is thrown.
Short, clean and easy to remember:
try { module.exports = exports = MyModule;} catch (e) {}
This file can be included in both the browser and node.js.
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: '!'};