-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
50 lines (43 loc) · 1.33 KB
/
index.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
const through = require('through2').obj;
const sharp = require('sharp');
const PluginError = require('plugin-error');
const ENABLED_FORMATS = ['png', 'jpg', 'jpeg', 'svg'];
const optionsByDefualt = {
quality: 90,
lossless: false,
speed: 5,
chromaSubsampling: '4:2:0'
}
function avif(options) {
return through(async (file, _, callback) => {
if (file.isNull()) {
callback(null, file);
return;
}
const ext = file.extname.slice(1).toLowerCase();
if (!ENABLED_FORMATS.includes(ext)) {
callback(null, file);
return;
}
const source = await sharp(file.contents);
source
.metadata()
.then((metadata) => {
if (metadata.format === 'svg' && options && (options.width || options.height)) {
source.resize(options.width, options.height);
}
return source
.avif(Object.assign(optionsByDefualt, options))
.toBuffer();
})
.then((stream) => {
file.contents = stream;
file.extname = '.avif';
callback(null, file);
})
.catch((err) => {
callback(new PluginError('gulp-avif', err, {fileName: file.path}));
});
});
}
module.exports = avif;