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,646 thoughts on “Using RequireJS exports with CoffeeScript

  1. Thanks for every other wonderful post. Where else could
    anybody get that type of information in such an ideal
    manner of writing? I’ve a presentation subsequent
    week, and I am on the look for such info.

  2. I do not even understand how I finished up here,
    however I assumed this submit was once good. I do not recognize who you might be but certainly you’re going to a well-known blogger in the event you aren’t
    already ;) Cheers!

    Here is my web page; seo services near me

  3. Greetings from California! I’m bored at work so I decided
    to check out your blog on my iphone during lunch break.
    I love the information you provide here and can’t wait to take a look when I get home.
    I’m shocked at how fast your blog loaded on my phone ..

    I’m not even using WIFI, just 3G .. Anyhow, wonderful blog!

    my homepage: are seo services worth it

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>