A
A
Artur Masloboev2016-05-18 23:37:48
gulp.js
Artur Masloboev, 2016-05-18 23:37:48

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);

Assembly functions:
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}`));
}

However, there is a problem when the pictures change, watch loops. I understand that you can send the processed files to another directory, then this will not happen, but I would like the pictures to remain in the same place.
If someone knows how to solve, I will be grateful.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
L
littleguga, 2016-05-19
@arthurmasl

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.

K
korobkovandrey, 2018-06-11
@korobkovandrey

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сек таймаута - больше не было такого
        */
    });
});

ps. for whom he did it - he himself is in IT, only in a different area, and why he needs it - I understand perfectly, as a result I set up several observers - pictures, for scss - when changing, main.css is collected from min.css with all other css , from it is already critical css and the site is already bypassing the browser cache, then sprites - I wanted a new svg or png icon - I threw it into the right folder - everything was rebuilt by itself - you can use it.
I absolutely agree - a local server, a dev server, a pre-production server, then only for production, and all this is collected only when all tests are performed after merging into master and in each its own env .. I would like to believe that this will happen someday, and if not so, it is perceived as something completely indecent.

T
timbellz, 2019-10-24
@timbellz

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);
}

Task run times are saved in memory and are lost when gulp exits. It will only save time during the watch task when running the images task for a second time.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question