Using RequireJS exports with CoffeeScript

If you are using the “exports” object in your RequireJS module definition and happen to also be using CoffeeScript then be careful to either return the exports object at the end of the function or explicitly return nothing from the function by typing “return” on the last line. Like so:

define((require, exports, module) ->
    exports.foo = 'bar'
    return
)

If you don’t return nothing or the exports object CoffeeScript will compile this:

define((require, exports, module) ->
    exports.foo = 'bar'
)

…to the following javascript:

define(function(require, exports, module) {
    return exports.foo = 'bar';
});

Where the return value will be the string ‘bar’. This is no good because if you return a value from your module definition function, RequireJs uses it instead of the exports object. So when you come to require your module, you’ll be passed a String, rather than an object with a “foo” property as you’d expect.

18,376 thoughts on “Using RequireJS exports with CoffeeScript

  1. Great blog! Do you have any helpful hints for aspiring writers?
    I’m hoping to start my own site soon but I’m a little
    lost on everything. Would you recommend starting with a free platform like WordPress or go for
    a paid option? There are so many choices out there that
    I’m totally overwhelmed .. Any tips? Thanks a lot!

  2. Hello there, I found your web site by the use of Google even as searching for a comparable topic, your site got
    here up, it seems to be good. I’ve bookmarked it in my google
    bookmarks.
    Hello there, simply turned into aware of your blog via Google, and located that it’s truly informative.
    I am gonna be careful for brussels. I will be grateful
    for those who continue this in future. Many other folks can be benefited from your writing.
    Cheers!

  3. Hi there, after reading this amazing article i am also delighted to share my know-how here with mates.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>