Writing AMD-API modules in CoffeeScript using RequireJS, quick and easy
Sample configuration file src/index.js:
requirejs.config({
baseUrl: 'app/',
paths: {
'cs': '../bower_components/require-cs/cs',
'coffee-script': '../bower_components/coffee-script/index',
'almond': '../bower_components/almond/almond'
},
// following options are irrelevant for in-browser usage;
// only evaluated during optimize build (via r.js):
stubModules: ['cs'],
exclude: ['coffee-script'],
include: 'cs!main',
insertRequire: ['cs!main'],
name: 'almond',
out: '../dist/index-optimized.js'
});
For a more detailed description of configuration options, see the fully documented r.js example build file.
When developing your app, simply reference RequireJS and the above configuration file
<script src="bower_components/requirejs/require.js" data-main="index.js"></script>
and reference CoffeeScript files via the "cs!" plugin name (see require-cs), e.g.:
require ['cs!test'], (test) ->
console.log test.testFunc()
CoffeeScript files are then fetched via XMLHttpRequest and compiled at runtime in the browser.
When building optimized and minified files for deployment the same configuration file can be used in RequireJS's optimization tool r.js. During optimization all required CoffeeScript files are compiled and script dependencies like the CoffeeScript compiler, RequireJS and require-cs itself are removed. However the Almond dependency is added for minimal AMD-API support.
Example using the grunt-contrib-requirejs wrapper for r.js:
grunt.initConfig
requirejs:
compile:
options:
mainConfigFile: 'src/index.js'
License
The MIT License (MIT)
Copyright (c) 2013 Oliver Hellebusch
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.