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.

7,410 thoughts on “Using RequireJS exports with CoffeeScript

  1. Howdy! Someone in my Myspace group shared this site with us so I came to look it over.
    I’m definitely loving the information. I’m bookmarking and will be tweeting this to my followers!
    Exceptional blog and excellent design.

  2. I was excited to find this website. I need to to thank you for your time due to this fantastic
    read!! I definitely really liked every bit of
    it and I have you book-marked to see new things on your
    web site.

  3. Sweet blog! I found it while searching on Yahoo News.
    Do you have any suggestions on how to get listed in Yahoo News?

    I’ve been trying for a while but I never seem to get there!

    Thank you

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>