Answer the question
In order to leave comments, you need to log in
How to make the images collected in the same directory?
Hello.
I'm trying to make sure that the added images are optimized and put in the same directory.
I put this watch:
gulp.watch([`**/*.{jpg,png,gif,svg}`], watchMedia);
function watchMedia() {
return gulp.src(`dev/assets/**/*.{gif,jpg,png,svg}`)
.pipe(newer('dev/assets/**'))
.pipe(imagemin({
progressive: true,
svgoPlugins: [{
removeViewBox: false
}, {
cleanupIDs: false
}],
use: [pngquant()]
}))
.pipe(gulp.dest(`${path.assets}`));
}
Answer the question
In order to leave comments, you need to log in
1. You don't have to want it. This is not a normal desire. There are sources, and there are compiled files.
2. If you just need to go to the same folder, then maybe you should at least change the name? Add min prefix, for example.
3. In general, this is absolutely normal and natural behavior of the watcher. But if you really need it right here, then assemble your terrible crutch:
at each run of the task, write the file name into the array, at the next watcher runs - check whether the file name is in the array or not, if not, run it, if there is - nothing do.
For littleguga 1 - this is a normal desire when the customer wants him to upload a picture to the directory that cms offers and it is optimized so that google page speed does not swear, 2 - for the same reason, the name cannot be changed, because with cms content it not connected (you can breed holivars as much as you like, that this can be done with cms plugins, etc. - it’s not possible, it can also be downloaded via ftp), 3 - the crutch is not so terrible, also wandered around the network in search of a solution, and I didn’t find it, I wrote my own, maybe someone who comes into this question will come in handy:
I use gulp-watch, I think you can adapt it to gulp.watch
var watch = require('gulp-watch');
gulp.task('watch:images', function() {
/*
сюда складируем пути входящих картинок, ниже объясню зачем
*/
var imagesFiles = [];
watch(['../images/**/*.{png,gif,jpg,jpeg}'], function (event, cb) {
setTimeout(function () {
/*
здесь получаем путь только измененной картинки, большая ошибка -
следить за картинками и при изменение любой -
прогонять все через imagemin
*/
var path = event.path;
/*
здесь проверяем существует ли картинка - event.stat -
вотчер срабатывает в том числе, если файл удалили,
event.path для файла выдает, а вот event.stat уже нет,
вторая проверка - нет ли картинки в списке только что
измененных картинок - чтобы не зациклить, об этом ниже
*/
if (event.stat && (imagesFiles.indexOf(path) < 0)) {
imagesFiles.push(path);
/*
объясняю зачем - строка выше добавляет путь в imagesFiles,
ниже setTimeout через 10 секунд очищает этот список, это нужно,
чтобы вотчер не зацикливался, в setTimeout в принципе можно хоть 1 сек поставить,
главное, чтобы это время было больше, чем время обработки одной картинки.
По мне - так 10 сек нормально.
*/
setTimeout(function () {
imagesFiles = [];
}, 10000);
/*
применяем только для измененной картинки, если их было несколько -
вотчер прогонит их по очереди
*/
gulp.src(path)
/*
imagemin вызываю другими плагинами (gifsicle - в поставке,
добавил gulp-jpegoptim и gulp-pngquant), как мне показалось - оптимизируют лучше,
но снижают качество, экспериментируйте с параметрами, svg отключил -
от спрайта на symbol оставляет только рожки
*/
.pipe(imagemin([
imagemin.gifsicle({interlaced: true}),
jpegoptim({progressive: true, max: 80, stripAll: true}),
pngquant()
]))
/*
следующее не просто gulp.dest('../images/') - при таком вызове картинки
из подпапок будут сохраняться в корне папке - оно нам не надо, поэтому вызов такой,
чтобы сохранялись по тем путям, где находятся
*/
.pipe(gulp.dest(function (file) {
return file.base;
}));
}
}, 1000);
/*
здесь таймаут так и не определился какой ставить, если вызывать совсем
без setTimeout - бывает на некоторых картинках вотчер совсем вылетает,
т.е. процессы gulp вообще исчезают, поставил 1сек таймаута - больше не было такого
*/
});
});
Incremental Builds
You can filter out unchanged files between runs of a task using the gulp.src function's since option and gulp.lastRun:
const paths = {
...
images: {
src: 'images/**/*.{jpg,jpeg,png}',
dest: 'images/'
}
}
function images() {
return gulp.src(paths.images.src, {since: gulp.lastRun(images)})
.pipe(imagemin({optimizationLevel: 5}))
.pipe(gulp.dest(paths.images.dest));
}
function watch() {
gulp.watch(paths.images.src, images);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question