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.

jQuery CDN as A Named Module In RequireJS

If you want RequireJS to fetch jQuery from a CDN, you’ll need to tell it to do so using the “paths” config:

require.config({
paths: {
"jquery": "https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"
}
});

As I understand it, if you want to use the local file fallback code a la html5bp you’re out of luck. For those of you who don’t know, the local file fallback code allows you to load jQuery from your own domain if the CDN version fails to load. It looks like this:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/vendor/jquery-1.8.2.min.js"><\/script>')</script>

Arguably, if you’re using jQuery it is likely to be a global requirement rather than a requirement for one or two modules. The same sort of thing with BackboneJS. It might be better to place these global requirements in the HTML for your pages (before the RequireJS script) to save typing ‘jquery’ and ‘backbone’ in all your module definitions.