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.

7,066 thoughts on “Using RequireJS exports with CoffeeScript

  1. Hello there! I could have sworn I’ve been to this web site before but after going through some of the articles I realized it’s new to me.
    Anyways, I’m certainly delighted I came across it and I’ll be bookmarking it and checking back regularly!

  2. Great blog! Do you have any helpful hints for aspiring writers?
    I’m planning to start my own blog soon but I’m a little lost on everything.
    Would you propose starting with a free platform like WordPress or go for
    a paid option? There are so many options out there that I’m
    completely overwhelmed .. Any ideas? Thank you!

  3. Hello there! I know this is kinda off topic but I was wondering if you knew where I
    could locate a captcha plugin for my comment form? I’m using the same blog platform as yours and I’m having trouble finding one?

    Thanks a lot!

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>