音の鳴るブログ

鳴らないこともある

gruntで変更のあったファイルだけ処理する

独立したスクリプトを grunt でそれぞれ watch して変更があったらコンパイルみたいなことをやっていたのだけど、毎回全ファイル処理すると時間がかかってイライラする。変更があったファイルだけ処理する方法が分からず、ずっと悩んでいたのだけどやっと出来たのでメモ。他に良い方法ありそうなので知っていたら教えてください。

  • とりあえず全ファイルを対象にする
  • 変更のあったファイルをメモっておいてフィルタリング
  • options:nospawn:true がないと子プロセスで呼ばれてメモった内容が消える

追記3

http://mohayonao.hatenablog.com/entry/2013/03/26/093554

追記2

コンパイルエラーがあった場合、grunt自体が止まるので良くなかった。。

追記

grunt-contrib-watch じゃなくて grunt-regarde だと nospawn:true が不要でしかも速いのでより便利です。

  grunt.event.on 'regarde:file:update', (name, rfile, tasks, spawn)->
    grunt.config.set 'changed', rfile

module.exports = (grunt)->
  'use strict'

  grunt.initConfig
    watch:
      coffee:
        files: 'public/**/*.coffee'
        tasks: 'coffee'
        options:
          nospawn: true
    coffee:
      files:
        expand: true
        src: 'public/**/*.coffee'
        ext: '.js'
        filter: (x)->
          changed = grunt.config.get 'changed'
          if changed then x is changed else true

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

  grunt.event.on 'watch', (action, filepath)->
    if action is 'changed'
      grunt.config.set 'changed', filepath