-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
46 lines (36 loc) · 1.35 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
const sharp = require('sharp')
, p = require('path')
;
module.exports = ({presets = [], ...options}) => (plugin) => {
plugin.registerTemplateHelper('srcset', (metadata, src, preset, attributes = {}) => {
// either get the sizes and srcset from the preset or extract them from the attributes
let sizes, srcset;
if (preset) {
if( !presets[preset]) throw new Error('Unknown srcset preset');
({sizes, srcset} = presets[preset]);
} else {
({sizes, srcset} = attributes);
}
const path = p.isAbsolute(src)
? src
: p.join('/', metadata.dirname, src)
;
const resizedFiles = srcset.map((width) => {
// add size to file name https://stackoverflow.com/a/10802339
const outputPath = path.substring(0, path.lastIndexOf('.')) + '-' + width + path.substring(path.lastIndexOf('.'));
plugin.enqueueFile(outputPath, async () => {
return plugin.getFile(path).then((file) => sharp(file, options).resize({width}).toBuffer());
});
return `${outputPath} ${width}w`;
});
attributes.sizes = sizes;
attributes.srcset = resizedFiles.join(',');
const output = ['<img'];
for (attribute in attributes) {
const value = attributes[attribute];
if (value !== false) output.push(` ${attribute}="${value}"`);
}
output.push('>');
return output.join('');
});
}