coffeescriptgruntjsgrunt-contrib-watchgrunt-contrib-coffee

grunt watch changes and restart coffee


I'm setting up a Gruntfile in which I'm trying to:

  1. Compile some coffeescript to javascript for client side.
  2. Watch for changes to the coffeescript that is to be compiled to javascript for clientside.
  3. Watch for changes to the backend (server) coffeescript files and restart the coffee app when changes are found.

I've got the first two steps working using this:

module.exports = (grunt) ->
  grunt.initConfig
    pkg: grunt.file.readJSON 'package.json'
    coffee:
      compile:
        expand: true
        flatten: true
        cwd: 'public/src'
        src: ['*.coffee']
        dest: 'public/dist'
        ext: '.js'
    watch:
      coffee:
        files: ['public/src/*.coffee']
        tasks: ['coffee']

  grunt.loadNpmTasks 'grunt-contrib-coffee'
  grunt.loadNpmTasks 'grunt-contrib-watch'
  grunt.registerTask 'default', ['coffee', 'watch']

But I'm not sure how to do the third step.

The directory structure currently looks like this:

app
  lib.coffee
  routes.coffee
public/
  dist/
    client.js
  src/
    client.coffee
Gruntfile.coffee
package.json
server.coffee

How would I watch for changes to anything within the app directory or to the server.coffee file and start the server (e.g. 'coffee server.coffee') automatically with grunt?

Also the server uses express - would restarting the app need to watch to see if the port was available again before being started?


Solution

  • Managed to get this working in the end:

    module.exports = (grunt) ->
      grunt.initConfig
        pkg: grunt.file.readJSON 'package.json'
        coffee:
          compile:
            expand: true
            flatten: true
            cwd: 'public/src'
            src: ['*.coffee']
            dest: 'public/dist'
            ext: '.js'
        watch:
          coffee:
            files: ['public/src/*.coffee']
            tasks: ['coffee']
          express:
            files: ['server.coffee']
            tasks: ['express:dev']
            options:
              spawn: false
        express:
          dev:
            options:
              script: 'server.coffee'
              opts: ['/path/to/coffee']
              #port: 8080
    
      grunt.loadNpmTasks 'grunt-contrib-coffee'
      grunt.loadNpmTasks 'grunt-contrib-watch'
      grunt.loadNpmTasks 'grunt-express-server'
      grunt.registerTask 'default', ['coffee', 'express:dev', 'watch']