I'm writing some grunt plugins. I'm using this.files.forEach
to iterate over source files. This seems to be the recommended solution. The code of a task looks, more or less, like this:
grunt.registerMultiTask(..., ..., function(){
// init
this.files.forEach(function (f) {
// do something
}
});
this.files
, console-logged, looks something like this:
[ { src: [Getter], dest: 'tmp/external-sources.json', orig: { src: [Object], dest: 'tmp/external-sources.json' } } ]
However I fell into trouble when there are no recognized source files. As far as I can see, the this.files.forEach
iterates over existing files, so the [Getter]
(don't know, what that is) doesn't execute an iteration for non-existent files.
Now, this is a problem for me, since I change file paths frequently. And if I misconfigure the new path, I don't get notified about invalid paths. The only way to handle this is to scan the long console output which is really frustrating for big projects. I'd like to be notified when source list is empty
The question is... in fact, the questions are: * how can I force grunt to shout, when there are no source files for a given task/target? * can I change this behavior globally? I mean, can I tell grunt to shout for empty source-list for all tasks? * did II misunderstand something? If so, please, correct me.
As far as I can see, the
this.files.forEach
iterates over existing files
The files
object contains all src
objects defined in your Gruntfile, including non existing files/paths. So it will iterate over non existing paths as well.
the
[Getter]
(don't know, what that is) doesn't execute an iteration for non-existent files
That's correct, the src
method in the files
object will only get an existing file.
I'd like to be notified when source list is empty
You can iterate over orig.src
for each of your files
and error handle from there.
Note that if your src
is undefined
or null
, grunt will warn you and abort, which is the behavior you're looking for. You can use the --force
flag to continue but I highly discourage it.
Example:
Gruntfile.js
module.exports = function(grunt) {
grunt.initConfig({
myTask: {
dev: {
files: [
{src: 'existingFile.js', dest: 'newFile'},
{src: 'nonExistingFile.js', dest: 'newFile2'}
]
}
}
});
grunt.loadTasks('my_tasks');
grunt.registerTask('default', ['myTask']);
};
my_tasks/task.js
module.exports = function(grunt) {
grunt.registerMultiTask('myTask', '', function() {
this.files.forEach(function(f) {
f.orig.src.forEach(function(src) {
//do something with src
});
});
});
};
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.