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

  1. It’s a shame you don’t have a donate button! I’d certainly donate to
    this excellent blog! I suppose for now i’ll settle for bookmarking
    and adding your RSS feed to my Google account. I look forward to fresh updates and
    will share this website with my Facebook group.

    Chat soon!

  2. I know this if off topic but I’m looking into starting my own weblog and was curious what all
    is required to get set up? I’m assuming having a blog like yours would cost
    a pretty penny? I’m not very web savvy so I’m not 100% sure.
    Any suggestions or advice would be greatly appreciated. Thank you

  3. Ligaments are the soft cells linking muscle to bone.

    Feel free to surf to my web-site; Tendon Repair Surgeon – Leonor,

  4. Greetings from Idaho! I’m bored at work so I decided to
    browse your website 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 surprised at how quick your blog loaded on my mobile ..
    I’m not even using WIFI, just 3G .. Anyways, superb site!

    my site best seo services in jalandhar

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>