LoginSignup
22
21

More than 5 years have passed since last update.

Gruntタスクを変更ファイルのみを対象に実行する

Posted at

こんな状況

coffeeフォルダの*.coffeeファイルを監視して,
jsフォルダに*.jsとして出力する。

Gruntfile.js
module.exports = function(grunt) {
    grunt.initConfig({
        watch: {
            files: 'coffee/*.coffee',
            tasks: 'coffee'
        },
        coffee: {
            compile: {
                expand: true,
                cwd: 'coffee',
                src: ['*.coffee'],
                dest: 'js',
                ext: '.js'
            }
        }
    }
};

これが問題

coffee/test01.coffeeを編集すると自動的にjs/test01.jsに変換される。
ただし変更ファイル以外も含め監視下のすべてのcoffeeファイルがコンパイルされる。

# ll coffee/ | awk '{print $8 " " $9}'

10:32 test01.coffee
10:30 test02.coffee

# ll js/ | awk '{print $8 " " $9}'

10:32 test01.js
10:32 test02.js

これをgrunt-newerで解決

tschaub/grunt-newer
https://github.com/tschaub/grunt-newer

タスク名の前にnewerをつけるだけで、
変更されたファイルのみを対象としてタスクが実行される。

Gruntfile.js
        watch: {
            files: 'coffee/*.coffee',
            tasks: 'newer:coffee'
        },

この状態であればcoffee/test01.coffeeを変更しても、
js/test01.jsのみ新たに生成されjs/test02.jsは変化しない。

# ll coffee/ | awk '{print $8 " " $9}'

10:36 test01.coffee
10:30 test02.coffee

# ll js/ | awk '{print $8 " " $9}'

10:36 test01.js
10:32 test02.js

ちょっと補足

time-gruntを使用して、出力結果を比較すると以下のようになる。

むしろnewerタスクの分遅くなってるが、これはプロジェクトの規模が極端に小さいため。
ファイル数やファイルサイズが大きくなれば、その効果は大きい(はず!)。

通常時

Execution Time (2014-06-15 01:32:04 UTC)
loading tasks    4ms  ▇▇▇▇ 8%
coffee:compile  46ms  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 92%
Total 50ms

grunt-newer使用時

Execution Time (2014-06-15 01:36:46 UTC)
loading tasks                  4ms  ▇▇ 6%
newer:coffee                   2ms  ▇ 3%
newer:coffee:compile           6ms  ▇▇▇ 10%
coffee:compile                48ms  ▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ 77%
newer-postrun...newer/.cache   2ms  ▇ 3%
Total 62ms
22
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
22
21