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.

17,636 thoughts on “Using RequireJS exports with CoffeeScript

  1. I am really impressed with your writing skills as well as with the layout on your weblog.
    Is this a paid theme or did you customize it yourself?
    Anyway keep up the nice quality writing, it’s rare to see
    a great blog like this one today.

  2. Right here is the right web site for anybody who wants to understand
    this topic. You understand so much its almost tough to argue with you (not that I really will need to…HaHa).
    You definitely put a new spin on a topic that has been written about for years.
    Great stuff, just wonderful!

  3. I do not even know the way I finished up here, but I believed this post was once
    great. I don’t recognize who you might be however definitely you’re going to a
    famous blogger in the event you are not already ;) Cheers!

    Feel free to visit my web blog :: seo services near me

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>