EternallyCurious
EternallyCurious

Reputation: 2415

Creating a file watcher for coffeescript with grunt

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.

Upvotes: 0

Views: 100

Answers (1)

hereandnow78
hereandnow78

Reputation: 14434

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'

Upvotes: 0

Related Questions