If I'm writing a JavaScript module for the browser, I'd assign it to window:
window.myModule = function(){ };
For node, I'd assign it to module.exports:
module.exports = function(){ };
What's the cleanest syntax for handling all scenarios? My current code is pretty gross:
(function(container, containerKey){
container[containerKey] = function(){ };
})(module ? module : window, module ? 'exports' : 'myModule');
I've seen examples like this, but the export is an object.
This answer is close, but I want to export directly to module (I don't want the extra qualifier).
Adapted from Multiple Files communication with coffeescript
Basically, we choose whether to run server-side or client-side code based on which environment we're in. This is the most common way to do it:
if(typeof module !== "undefined" && module.exports) {
//On a server
module.exports = ChatService;
} else {
//On a client
window.ChatService = ChatService;
}
To get it:
if(typeof module !== "undefined" && module.exports) {
//On a server
ChatService = require("ChatService.coffee");
} else {
//On a client
ChatService = window.ChatService;
}
The else clause of the second block can be skipped, since ChatService already refers to the reference attached to window.
Note that your current code will crash with a ReferenceError on the client, unless module happens to be declared somewhere.