Monitoring Document Changes in Gulp
It's not very convenient to call a command in the console every time you need to perform some transformation - after all, when writing code, you have to do this very often.
Therefore, Gulp has a built-in special function
watch
for monitoring file changes.
When any of the tracked files changes,
the corresponding task will be launched
automatically.
Let's look at an example of converting LESS to CSS. First, let's connect everything we need:
let {src, dest, watch} = require('gulp');
let less = require('gulp-less');
Now let's create a task for the conversion:
function task(cb) {
return src('src/*.less')
.pipe(less())
.pipe(dest('dist'));
}
Now let's export an anonymous function, inside which we will track changes to our files, calling our task in this case:
exports.default = function() {
watch('src/*.less', task);
};
After launch, an "endless" task will be running
in the command line. This means that you won't be able
to enter other commands into this terminal. You can stop
such a task by pressing the combination
Ctrl + C
in the terminal.
You can monitor different groups of files, assigning different tasks to them:
exports.default = function() {
watch('src/*.less', task1);
watch('src/*.sass', task1);
};
Or you can execute a series of tasks for one group:
exports.default = function() {
watch('src/*.less', series(task1, task2));
};
Suppose you have a group of JavaScript files. Make it so that these files are merged into one file, and then minimization of that file is performed. Make sure the task is executed when any of our files changes.