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

  1. I am really enjoying the theme/design of your blog.
    Do you ever run into any web browser compatibility issues?
    A small number of my blog visitors have complained about my blog not working correctly in Explorer
    but looks great in Firefox. Do you have any suggestions to help fix this issue?

    Have a look at my web-site … Best seo company near me

  2. I absolutely love your blog and find nearly all of your post’s to be just
    what I’m looking for. Do you offer guest writers to write content for yourself?
    I wouldn’t mind creating a post or elaborating on many of the subjects you write concerning here.
    Again, awesome site!

  3. Occasionally your attorney will certainly suggest going to trial.

    My web-site … california dui lawyer reviews (Jeramy)

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>