2

我正在使用 gulp 来调整和重命名一些图像:

var gulp = require('gulp');
var imageResize = require('gulp-image-resize');
var changed = require('gulp-changed');
var rename = require('gulp-rename');

var resizeImages = function resize(options) {
  gulp
    .src('original-images/**')
    .pipe(changed('./'))
    .pipe(imageResize({ width: options.width }))
    .pipe(rename((path) => { path.basename += options.fileSuffix; }))
    .pipe(gulp.dest('public/assets/img/'));
};


gulp.task('resize-images', () => {
  const desktopImageResizeOptions = {
    width: 356,
    fileSuffix: '-desktop',
  };
  const tabletImageResizeOptions = {
    width: 291,
    fileSuffix: '-tablet',
  };
  const phoneImageResizeOptions = {
    width: 721,
    fileSuffix: '-phone',
  };
  resizeImages(desktopImageResizeOptions);
  resizeImages(tabletImageResizeOptions);
  resizeImages(phoneImageResizeOptions);
});

这有效 - 它将调整大小的重命名图像放入正确的位置,并在文件名中添加后缀。

但是,它也会创建名为-desktop-phone的目录-tablet。我怎样才能防止这种情况发生?

4

2 回答 2

0

我通过指定文件结尾解决了它,因此没有传入目录。所以第 8 行的 src 变成了

.src('original-images/**/*.{jpg,png}')
于 2015-12-02T21:09:51.153 回答
0

您还可以处理更复杂的情况。如果传递给函数的rename函数不改变文件的路径,它将被省略。在以下示例中,如果文件没有extname

.pipe(rename(function (path) {
    if (path.extname !== "") {
        path.basename += "-" + options.width;
    }            
}))
于 2016-02-09T19:56:51.020 回答