0

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

Community
  • 1
  • 1
bendytree
  • 13,095
  • 11
  • 75
  • 91
  • Had a look at [browserify](https://github.com/substack/node-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 Jun 06 '13 at 16:53
  • Otherwise i think one of the solutions offered [here](http://stackoverflow.com/questions/13673346/supporting-both-commonjs-and-amd) should work for functions as well as objects – Andreas Hultgren Jun 06 '13 at 16:55
  • possible duplicate of [Multiple Files communication with coffeescript](http://stackoverflow.com/questions/9287510/multiple-files-communication-with-coffeescript) – Aaron Dufour Jun 06 '13 at 17:18
  • @AaronDufour Your link is a question about coffeescript, plus the accepted answer assigns a module with an extra qualifier. – bendytree Jun 06 '13 at 17:45
  • @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 Jun 06 '13 at 17:53

1 Answers1

0

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.

Community
  • 1
  • 1
Aaron Dufour
  • 17,288
  • 1
  • 47
  • 69