【问题标题】:Grunt - lint only modified files using grunt-newerGrunt - 使用 grunt-newer 仅对修改过的文件进行 lint
【发布时间】:2013-11-18 13:40:31
【问题描述】:

我正在运行一个 Grunt 任务,该任务使用 Concurrent 来运行 Nodemon 和 Watch/Livereload。在默认加载时,我 lint 并启动 Concurrent。我还想设置一个 Watch 在更改时对单个文件进行 lint。目前,当任何一个文件被更改时,所有文件都会被 lint。

我在 StackOverflow 上检查了一个类似的问题,并决定使用 grunt-newer 作为潜在的解决方案。然而,在我下面的实现中,“较新”前缀似乎没有做任何事情。如何解决此问题,以便仅对更改的文件进行 linted?

module.exports = function(grunt) {
  //load all dependencies
  require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);

  grunt.initConfig({
    pkg: grunt.file.readJSON('package.json'),
    concurrent: {
      dev: {
        options: {
          logConcurrentOutput: true
        },
        tasks: ['watch', 'nodemon']
      }
    },
    jshint: {
      files: ['Gruntfile.js', 'client/src/*.js', 'server/**/*.js'],
      options: {
        '-W030': true,
        '-W083': true,
        globals: {
          console: true,
          module: true,
          document: true
        }
      }
    },
    watch: {
      all: {
        files: ['<%= jshint.files %>'],
        tasks: ['newer:jshint']
      },
      frontend: {
        files: ['client/**/*.{css,js,html}'],
        options: {
          livereload: true
        }
      }
    },
    nodemon: {
      dev: {
        options: {
          file: 'server/server.js',
          watchedFolders: ['server']
        }
      }
    }
  });

  grunt.registerTask('test', ['jshint']);
  grunt.registerTask('default', ['jshint', 'concurrent']);

};

【问题讨论】:

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


    【解决方案1】:

    我遇到了同样的问题,终于解决了。该解决方案隐藏在文档深处,并且与代码示例中的spawn 选项非常误导:https://github.com/gruntjs/grunt-contrib-watch#compiling-files-as-needed

    您的配置文件应该与您在问题中的配置文件保持一致,但您需要为监视事件添加一个侦听器。我推荐他们提供的“强大”选项(为您特定的任务配置进行了修改)。将此代码放在对grunt.initConfig 的调用上方以及require 调用之后。

    var changedFiles = Object.create(null);
    var onChange = grunt.util._.debounce(function() {
      // Modified to point to jshint.files as per the task example in the question.
      grunt.config('jshint.files', Object.keys(changedFiles));
      changedFiles = Object.create(null);
    }, 200);
    
    grunt.event.on('watch', function(action, filepath) {
      changedFiles[filepath] = action;
      onChange();
    });
    

    nospawn 选项添加到all 监视任务。这是文档中的误导。它提到如果你想动态修改你的配置应该禁用它,但基本上阻止它使用更新,除非它设置为true

     watch: {
       all: {
         files: ['<%= jshint.files %>'],
         tasks: ['newer:jshint'],
         options: {
           nospawn: true,
         }
       },
       ...
    

    注意:如果您在运行时修改 grunt 文件,那么它将对所有文件进行 lint,不知道为什么会这样做,但随后会卡住,并且会继续对您所做的所有更改进行 linting。我刚刚从应该删除以避免它的文件列表中取出“gruntfile.js”。

    【讨论】:

    • 完美!感谢您修改后的答案。
    猜你喜欢
    • 1970-01-01
    • 2014-11-03
    • 1970-01-01
    • 2015-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-11
    相关资源
    最近更新 更多