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.

6,714 thoughts on “Using RequireJS exports with CoffeeScript

  1. With havin so much content and articles do you ever
    run into any problems of plagorism or copyright violation? My website has a lot of
    exclusive content I’ve either created myself or outsourced but it appears a lot of
    it is popping it up all over the web without my agreement.
    Do you know any methods to help protect against content from being ripped off?

    I’d certainly appreciate it.

  2. I am truly happy to read this weblog posts which consists
    of lots of helpful information, thanks for providing these
    kinds of information.

  3. I loved as much as you’ll receive carried out right here.
    The sketch is tasteful, your authored subject matter stylish.

    nonetheless, you command get got an edginess over that you
    wish be delivering the following. unwell unquestionably come more formerly
    again since exactly the same nearly a lot often inside case
    you shield this increase.

  4. You actually make it seem so easy with your presentation but
    I find this matter to be actually something which I think I would never understand.

    It seems too complex and extremely broad for me.

    I’m looking forward for your next post, I will try
    to get the hang of 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>