我正在运行一个 Grunt 任务,该任务使用 Concurrent 来运行 Nodemon 和 Watch/Livereload。在默认负载下,我检查并启动 Concurrent。我还想设置一个监视来检查更改时的各个文件。目前,当任何一个文件发生更改时,所有文件都会被检查。
我在 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']);
};
最佳答案
我也遇到了同样的问题,最后解决了。该解决方案隐藏在文档深处,并且与代码示例中的 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 检测,不知道为什么要这样做,但随后它会卡住,并且只会针对您所做的所有更改继续对所有文件进行 lint 检测。我刚刚从应该检查以避免它的文件列表中取出了“gruntfile.js”。
关于gruntjs - Grunt - 使用 grunt-newer 仅对修改过的文件进行 lint,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19826985/