-
Notifications
You must be signed in to change notification settings - Fork 0
/
gulpfile.js
122 lines (110 loc) · 3.59 KB
/
gulpfile.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
const gulp = require('gulp');
const scaleImages = require('gulp-scale-images');
const readMetadata = require('gulp-scale-images/read-metadata');
const flatMap = require('flat-map').default;
const del = require('del');
const glob = require('glob');
const IMG_GLOB = '**/*.{jpeg,jpg,png,webp}';
const SRC = 'images';
const DEST = 'public';
const IMG_ARRAY = 'array';
const IMG_PROMISE = 'promise';
gulp.task('build:image-array', () => {
const createImages = (file, cb) => {
readMetadata(file, (err, meta) => {
if (err) {
return cb(err);
}
const formats = [meta.format, 'webp'];
const sizes = [200, 300, 400];
const files = [];
const commonScale = {
maxWidth: Math.trunc(meta.width * 0.5),
withoutEnlargement: false,
fit: 'cover',
rotate: true,
metadata: false,
};
formats.forEach((format) => {
sizes.forEach((width) => {
const img = file.clone();
img.scale = {
...commonScale,
format,
maxWidth: width,
};
img.dirname = `${img.dirname}/${width}`;
files.push(img);
});
});
cb(null, files);
});
};
return gulp
.src(`${SRC}/${IMG_GLOB}`)
.pipe(flatMap(createImages))
.pipe(scaleImages())
.pipe(gulp.dest(`${DEST}/${IMG_ARRAY}`));
});
gulp.task('build:image-promise', () => {
const createImages = (file, cb) => {
cb(
null,
new Promise((resolve, reject) => {
readMetadata(file, (err, meta) => {
if (err) {
return reject(err);
}
const formats = [meta.format, 'webp'];
const sizes = [200, 300, 400];
const files = [];
const commonScale = {
maxWidth: Math.trunc(meta.width * 0.5),
withoutEnlargement: false,
fit: 'cover',
rotate: true,
metadata: false,
};
formats.forEach((format) => {
sizes.forEach((width) => {
const img = file.clone();
img.scale = {
...commonScale,
format,
maxWidth: width,
};
img.dirname = `${img.dirname}/${width}`;
files.push(img);
});
});
resolve(files);
});
})
);
};
return gulp
.src(`${SRC}/${IMG_GLOB}`)
.pipe(flatMap(createImages))
.pipe(scaleImages())
.pipe(gulp.dest(`${DEST}/${IMG_PROMISE}`));
});
gulp.task('clean', () => {
return del(DEST);
});
gulp.task('count', (cb) => {
console.log(
`Task "build:image-array" return ${
glob.sync(`${DEST}/${IMG_ARRAY}/${IMG_GLOB}`).length
} files.`
);
console.log(
`Task "build:image-promise" return ${
glob.sync(`${DEST}/${IMG_PROMISE}/${IMG_GLOB}`).length
} files.`
);
cb();
});
gulp.task(
'default',
gulp.series('clean', 'build:image-array', 'build:image-promise', 'count')
);