-
Notifications
You must be signed in to change notification settings - Fork 1
/
.eleventy.js
56 lines (48 loc) · 1.45 KB
/
.eleventy.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
const Image = require('@11ty/eleventy-img');
const cheerio = require('cheerio');
async function imageShortcode(src, alt, sizes) {
let metadata = await Image(src, {
widths: [300, 600],
formats: ["avif", "jpeg"]
});
let imageAttributes = {
alt,
sizes,
loading: "lazy",
decoding: "async",
};
// You bet we throw an error on missing alt in `imageAttributes` (alt="" works okay)
return Image.generateHTML(metadata, imageAttributes);
}
module.exports = function (eleventyConfig) {
eleventyConfig.addPassthroughCopy('img')
eleventyConfig.addPassthroughCopy('styles.css')
eleventyConfig.addExtension('md', {
read: true,
compile() {
return async function render(data) {
const html = await this.defaultRenderer(data);
const $ = cheerio.load(html);
if (data.tags?.includes('blog')) {
await Promise.all(
// loop over all the images in our document
$('img').toArray().map(async (img) => {
// grab the image attributes
const { src = '', alt = '', sizes = '100vw' } = img.attribs;
// convert to an optimized image
const optimizedImage = await imageShortcode(src, alt, sizes);
// replace our images with an optimized one
$(img).replaceWith(optimizedImage);
})
)
}
return $.html();
}
}
})
return {
dir: {
input: 'src'
}
}
}