LoginSignup
5
4

More than 5 years have passed since last update.

watch中に変更したファイルのみeslintをかける(grunt, gulp)

Posted at

eslintのconfigファイルを変更した時など、一旦、変更のあったjsファイルのみにeslintをかけたい時もあると思います。意外と投稿されていなかったので、投稿いたします。

grunt

grunt-contrib-watchのみで可能です。

Gruntfile.js
 module.exports = function(grunt) {
  grunt.initConfig({

    watch: {
     scripts: {
      files: '**/*.js',
      tasks: ['eslint'],
      options: {
        spawn: false, <- *1
      },
     },
   },

   eslint: {
        target: ['**/**.js']
   }
  });

  grunt.event.on('watch', function(action, filepath, target){ <- *2
    if (target == js) {
     grunt.config(['eslint', 'target']);
    }
  });

  // Load the plugins
  grunt.loadNpmTasks('grunt-contrib-watch');

  // Tasks
  grunt.registerTask('default', ['watch']);
};

1 watchタスクにspawnオプション追加

一時的な設定の変更を許可する。
nospawn: true でも可能ですがv0.5.0からspawnが導入されているので、spawnの方が良いかと。

2 イベントリスナーを設定 grunt.event.on('watch', function())

grunt.configにて一時的にeslintタスクの設定を変更
grunt.config.setと同様

gulp

gulp-cachedが必要になります。
※あくまでキャッシュなので、初期実行時は全てのファイルのエラーが出ます。その後に変更したjsファイルのみエラーが出力されます。よって、gulp-plumber等は必須になります。

gulp.js
// gulp-cached
var cached = require('gulp-cached');

// eslint
var eslint = require('gulp-eslint');

gulp.task('eslint', function () {
  return gulp.src(path.js_src)
    .pipe(cached('eslint')) <- *1
    .pipe(plumber({
      errorHandler: notify.onError('<%= error.message %>')
    }))
    .pipe(eslint())
    .pipe(eslint.format());
});

// task
gulp.task('default', function () {
  gulpSequence('build', 'eslint', 'watch')(); <- *2
});

2 watchの前に初期実行しておく

この対応によって、変更したタイミングでそのjsファイルのみeslintがかかります。

gulp-changedが推奨される場合も

ビルド後のファイル群に対するタスクであれば、gulp-changedで行えます。

5
4
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
5
4