使用grunt为coffeescript创建文件监视器

时间:2014-05-28 16:35:53

标签: gruntjs grunt-contrib-watch grunt-contrib-coffee

我正在尝试使用grunt watch插件(https://www.npmjs.org/package/grunt-contrib-watch)来创建自定义文件监视器。我正在为coffeescript文件编写编译脚本,以便在更改时进行编译。这是基本配置。

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)

我需要将文件路径作为输入,以便能够对文件执行编译并将输出保存在相对于源coffeescript文件的文件路径的目录中。在我上面写的代码中,未定义的文件路径值传递 - 我可以在日志输出中看到。请帮我获取修改文件的文件路径,以便我可以相应地动态配置coffeescript编译器。

1 个答案:

答案 0 :(得分:0)

您需要在watch事件中注册处理程序。在那里,您将获得可用于配置咖啡任务的文件路径:

(代码未经测试,但我认为你明白了)

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'
相关问题