When I create a new coffeescript file, I cannot access the code in the compiled code from another file because it gets wrapped in some function scope. For example:
CoffeeScript:
class ChatService
constructor: (@io) ->
Generated Javascript:
(function() {
var ChatService;
ChatService = (function() {
function ChatService(io) {
this.io = io;
}
return ChatService;
})();
}).call(this);
When trying to call ChatService in another file, it’s not defined. How do I handle multiple files with coffeescript?
Depending on whether this is client- or server-side code, there are two slightly different approaches.
Client-side: Here we attach things that should be available across files to the global namespace (
window) as follows:Then, in another file both
ChatServiceandwindow.ChatServicewill allow access to the class.Server-side: Here we must use
exportsandrequire. In theChatService.coffeefile, you would have the following:Then, to get at it from another file you can use:
Note: If there are multiple classes that you are getting from ChatService.coffee, this is one place where CoffeeScript’s dict unpacking really shines, such as:
Both: Basically, we choose whether to run server-side or client-side code based on which environment we’re in. A common way to do it:
To get it:
The else clause of the second block can be skipped, since
ChatServicealready refers to the reference attached towindow.If you’re going to define a lot of classes in this file, it may be easier to define them like:
And then attach them like
module.exports = selfon the server and_.extend(window, self)on the client (replace_.extendwith anotherextendfunction as appropriate).