Skip to content

Instantly share code, notes, and snippets.

@jjmalina
Created August 27, 2013 16:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jjmalina/6355995 to your computer and use it in GitHub Desktop.
Save jjmalina/6355995 to your computer and use it in GitHub Desktop.
Using grunt-contrib-watch and grunt-contrib-coffee to only compile files as needed
# It's pretty annoying to get single CoffeeScript file compilation with grunt-contrib-coffee
# and grunt-contrib-watch because it doesn't work out of the box.
#
# This is an open issue and it depends on how your project is structured and how your tasks are configured.
# See: https://github.com/gruntjs/grunt-contrib-watch/issues/149
#
# Below is my simple solution which in a sort of hacky way alters the grunt config object at runtime.
module.exports = (grunt) ->
grunt.config.init
coffee:
default:
expand: true
cwd: 'source/scripts'
src: ['**/*.coffee']
dest: 'compiled/scripts'
ext: '.js'
tests:
expand: true
cwd: 'tests/source'
src: ['**/*.coffee', '../*.coffee']
dest: 'tests/compiled'
ext: '.js'
watch:
coffee:
files: ['source/scripts/**/*.coffee', 'tests/source/**/*.coffee']
tasks: ['coffee']
options:
spawn: false # spawn must be false for this to work
grunt.loadNpmTasks('grunt-contrib-coffee')
grunt.loadNpmTasks('grunt-contrib-watch')
grunt.event.on 'watch', (action, filepath) ->
# this is a bit of a hack so that we can compile coffescript files
# only as they're needed.
if filepath.substring(0, 6) is "source"
relative = filepath.replace(grunt.config('coffee.default.cwd') + "/", "")
grunt.config('coffee.default.src', [relative])
grunt.config('coffee.tests.src', [])
else if filepath.substring(0, 5) is "tests"
relative = filepath.replace(grunt.config('coffee.tests.cwd') + "/", "")
grunt.config('coffee.default.src', [])
grunt.config('coffee.tests.src', [relative])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment