有几个选择:
1 - 您可以使用自定义过滤功能 https://github.com/gruntjs/grunt/wiki/Configuring-tasks#custom-filter-function过滤 jshint 文件模式返回的文件列表。像这样的东西:
module.exports = function(grunt) {
var fs = require('fs');
var myLibsPattern = ['./mylibs/**/*.js'];
// on linux, at least, ctime is not retained after subsequent modifications,
// so find the date/time of the earliest-created file matching the filter pattern
var creationTimes = grunt.file.expand( myLibsPattern ).map(function(f) { return new Date(fs.lstatSync(f).ctime).getTime() });
var earliestCreationTime = Math.min.apply(Math, creationTimes);
// hack: allow for 3 minutes to check out from repo
var filterSince = (new Date(earliestCreationTime)).getTime() + (3 * 60 * 1000);
grunt.initConfig({
options: {
eqeqeq: true,
eqnull: true
},
jshint: {
sincecheckout: {
src: myLibsPattern,
// filter based on whether it's newer than our repo creation time
filter: function(filepath) {
return (fs.lstatSync(filepath).mtime > filterSince);
},
},
},
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.registerTask('default', ['jshint']);
};
2 - 使用grunt-contrib-watch 插件 https://github.com/gruntjs/grunt-contrib-watch检测文件何时发生更改。然后您可以从事件中读取文件列表,如中所述这条评论 https://github.com/gruntjs/grunt-contrib-watch凯尔·罗宾逊·杨(Kyle Robinson Young)(“莎玛”):
grunt.initConfig({
watch: {
all: {
files: ['<%= jshint.all.src %>'],
tasks: ['jshint'],
options: { nospawn: true }
}
},
jshint: { all: { src: ['Gruntfile.js', 'lib/**/*.js'] } }
});
// On watch events, inject only the changed files into the config
grunt.event.on('watch', function(action, filepath) {
grunt.config(['jshint', 'all', 'src'], [filepath]);
});
这不exactly满足您的要求,因为它取决于您开始修改文件时手表是否立即运行,但它可能更适合整体 Grunt 方法。
也可以看看这个问题 https://stackoverflow.com/questions/12063266/how-do-you-watch-multiple-files-but-only-run-task-on-changed-file-in-grunt-js但要注意其中一些与旧版本的 Grunt 和 Coffeescript 有关。
UPDATE:现在有一个较新的咕噜声 https://github.com/tschaub/grunt-newer插件以更优雅的方式处理这一切