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

  1. Have you ever thought about adding a little bit more than just your articles?
    I mean, what you say is fundamental and all. However think about
    if you added some great visuals or video clips to give your posts more, “pop”!
    Your content is excellent but with pics and clips, this blog could certainly be one of the most beneficial in its field.

    Amazing blog!

  2. Sweet blog! I found it while surfing around 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

  3. I’m really enjoying the design and layout of your blog. It’s a very easy on the eyes which makes it much more enjoyable for me to come here and visit more often. Did you hire
    out a designer to create your theme? Exceptional work!

  4. Every weekend i used to pay a visit this website, as i
    wish for enjoyment, since this this website conations in fact fastidious funny
    information too.

  5. This article will help the internet users for building up new weblog or even a blog from start to end.

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>