0

I am trying to use the grunt watch plugin (https://www.npmjs.org/package/grunt-contrib-watch) to create custom filewatchers. I am writing compile scripts for coffeescript files to be compiled when they are changed. Here is the basic configuration.

grunt.initConfig(
    pkg: grunt.file.readJSON 'package.json'
    watch:
      cofee_files:
        files: ['client/**/*.coffee'],
        tasks: ['start'],
        options:
          spawn: false,

grunt.registerTask( 'start', 'starting coffee compilation', (filepath)->
    console.log(filepath)

I need to get the filepath as an input to be able to perform compilation on the file and save the output in a directory relative to the filepath of the source coffeescript file. In the code I have written above, the filepath value passed in undefined - which I can see on the log output. Please help me obtain the filepath of the modified file so I can dynamically config the coffeescript compiler accordingly.

EternallyCurious
  • 2,345
  • 7
  • 47
  • 78

1 Answers1

0

you need to register a handler to the watch event. there you will get the filepath which you can use to configure your coffee-task:

(code untested, but i think you get the idea)

path = require 'path'

grunt.initConfig(
  pkg: grunt.file.readJSON 'package.json'

  watch:
    cofee_files:
      files: ['client/**/*.coffee'],
      tasks: ['start'],
      options:
        spawn: false,
  coffee:
    compile: 
      files: []


  grunt.event.on 'watch', (action, filepath) ->
    # modify your coffee task here
    newCoffeeConfig = 
      cwd: path.dirname(filepath)
      src: path.basename(filepath)
      dest: path.dirname(filepath)
      ext. '.js' 

    grunt.config.get('coffee:compile.files').push newCoffeeConfig
    grunt.task.run 'coffee:compile'
hereandnow78
  • 14,094
  • 8
  • 42
  • 48
  • Sorry. I got a false positive earlier. The code creates an error: `Fatal error: Cannot call method 'push' of undefined`. I've also tried compiling as `grunt.config.get('coffee:compile')` which does not work either. Can you please provide the syntactically accurate code? – EternallyCurious May 29 '14 at 04:19
  • 1
    idention of grunt.event.on 'watch' was wrong, i corrected it. moreover SO is a board to help you understand things, but not to do your work! there must be some kind of transfer done by yourself... – hereandnow78 May 31 '14 at 14:47