Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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).

share|improve this question
Had a look at browserify? The drawback is that it requires you to run a build script and use different files for browser and node. And some hacks to make it available on window instead of through "require()" in the browser. – Andreas Hultgren 2 days ago
Otherwise i think one of the solutions offered here should work for functions as well as objects – Andreas Hultgren 2 days ago
possible duplicate of Multiple Files communication with coffeescript – Aaron Dufour 2 days ago
@AaronDufour Your link is a question about coffeescript, plus the accepted answer assigns a module with an extra qualifier. – bendytree 2 days ago
@bendytree The translation to javascript requires just a few extra parens, and I thought it was pretty close, but I'd be happy to make the small changes and repost it here. – Aaron Dufour 2 days ago

1 Answer

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.