[英]Why gulp-watch doesn't delete files
I'm trying to make my gulp-watch task to delete files from /dest
directory when I delete them from /src
, but it doesn't work. 当我从
/src
删除文件时,我试图使我的gulp-watch任务从/dest
目录中删除文件,但这是行不通的。 Where is the mistake? 错误在哪里?
var watch = require('gulp-watch'); var imagemin = require('gulp-imagemin'); var del = require('del'); var pngquant = require('gulp-pngquant'); var imgSrc = 'src/img/**'; var imgDst = 'build/img'; gulp.task('del', function() { return del('build'); }); gulp.task('img', function() { return gulp.src(imgSrc) .pipe(debug({title: 'src'})) //.pipe(newer(imgDst)) .pipe(imagemin()) .pipe(debug({title: 'imagemin'})) .pipe(gulp.dest(imgDst)) .pipe(debug({title: 'dest'})); }); gulp.task('watch', function () { var watcher = gulp.watch(imgSrc, ['img']); watcher.on('change', function (event) { if (event.type === 'deleted') { var filePathFromSrc = path.relative(path.resolve(imgSrc), event.path); var destFilePath = path.resolve(imgDst, filePathFromSrc); del.sync(destFilePath); } }); });
Your destFilePath
points to a file that doesn't exist. 您的
destFilePath
指向一个不存在的文件。 If you delete a file src/img/foo.png
your destFilePath
variable ends up pointing to build/foo.png
instead of build/img/foo.png
(which is where your img
task has put it). 如果删除文件
src/img/foo.png
destFilePath
变量最终指向build/foo.png
而不是build/img/foo.png
(这是img
任务放置的位置)。
The reason is that you're applying path.relative()
to imgSrc
which contains **
. 原因是您要将
path.relative()
应用于包含**
imgSrc
。 However path.relative()
doesn't unterstands globs. 但是
path.relative()
并不能理解glob。 It just interprets **
as a regular directory name. 它只是将
**
解释为常规目录名称。 So you end up being one directory off. 因此,您最终将成为一个目录。
You need to leave out the **
when you use path.relative()
: 使用
path.relative()
时,您需要path.relative()
**
:
if (event.type === 'deleted') {
var filePathFromSrc = path.relative(path.resolve('src/img'), event.path);
var destFilePath = path.resolve(imgDst, filePathFromSrc);
del.sync(destFilePath);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.