Recently I had to keep two folders in sync with gulp. I needed to copy all files from one folder to another, and keep them up to date when changes were made.
The easy way is just to copy the entire folder every time.
gulp.task('watch-folder', function() {
gulp.watch('./source/**/*', ['copy-folder']);
});
gulp.task('copy-folder', function() {
gulp.src('./source/**/*')
.pipe(gulp.dest('./dest'));
});
However, my source folder was very large. I wanted to copy the entire folder on gulp start, and then only copy changed or modified files.
The default gulp.watch
task doesn't work on new or deleted files, so I had to turn to a plugin, gulp-watch. Installation is easy:
npm install --save-dev gulp-watch
Their example shows this working out of the box, however, it will give you unexpected results if you don't use the base
option.
Here's the full snippet:
var watch = require('gulp-watch');
var source = './source-folder',
destination = './dest-folder';
gulp.task('watch-folder', function() {
gulp.src(source + '/**/*', {base: source})
.pipe(watch(source, {base: source}))
.pipe(gulp.dest(destination));
});
Without the base
option, it would copy source-folder/file.png
to dest-folder/source-folder/file.png
which is almost certainly not what you want.
One downside is you can't pipe to gulp tasks from watch
, so as far as I can tell, you can't have watch-folder
and copy-folder
like in the first example.
That's it!
If this tip helped you, consider following me on Twitter or buying me a coffee :).