Created
July 22, 2018 07:26
-
-
Save AlexandroPerez/4a104bc6ecf9c10aadecbe8acbb7fcd8 to your computer and use it in GitHub Desktop.
Example of gulp-responsive and gulp-newer when doing 1:many images
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import gulp from 'gulp'; | |
import responsive from 'gulp-responsive'; | |
import newer from 'gulp-newer'; | |
import rename from 'gulp-rename'; | |
/** | |
* NOTE: this has a flaw, as if one of the multiple images is deleted, | |
* gulp-newer will only check against one of them, so it will not | |
* create the missing image(s). Use only as a way to process new images | |
* only, not as a foolproof way to have all your responsive images always | |
* available. | |
* | |
* Tis task uses gulp-responsive to create multiple files, gulp-newer | |
* to make sure only new images are processed, and gulp-rename so that | |
* gulp-newer has a file to compare against in destination. | |
* | |
* NOTE: rename is only needed if the images produced by gulp-responsive | |
* will all have different names from the original. In the below example | |
* an image called "cat.jpg" will output "cat-small.jpg", "cat-medium.jpg" | |
* and "cat-large.jpg", so we need to pipe the original through rename so | |
* gulp newer can check it against any of the suffixed files, then change | |
* the filename back to the original by removing the suffix | |
* | |
* It can be alot easier to just keep the large image "cat-large.jpg" without | |
* a suffix, and use it as "cat.jpg". this way we can avoid using gulp rename | |
* and in gulp-responsive, we output one image without any suffixes. That image | |
* will serve as the file gulp-newer can compare against. | |
**/ | |
export function jpgImages() { | |
return gulp.src('src/img/**/*.jpg') | |
.pipe(rename( {suffix: '-large'} )) // necessary for gulp-newer to work, so it can compare | |
.pipe(newer('dist/img/')) // against a single destination file. Basically adding one | |
.pipe(rename( opt => { // of the suffixes on the fly, then renaming back. | |
opt.basename = opt.basename.replace('-large', ''); | |
return opt; | |
} )) | |
.pipe(responsive({ | |
// Resize all jpg images to three different sizes: 280, 400 and 800 | |
'**/*.jpg': [{ | |
width: 280, | |
quality: 30, | |
rename: { suffix: '-small'} | |
}, { | |
width: 400, | |
quality: 40, | |
rename: { suffix: '-medium'} | |
}, { | |
width: 800, | |
quality: 50, | |
rename: { suffix: '-large'} | |
}] | |
}, { | |
// needed to avoid errors when images aren't "newer" | |
// since gulp-responsive won't have anything to do. | |
errorOnUnusedConfig: false | |
})) | |
.pipe(gulp.dest("dist/img/")); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment