eleventy-img-helper

eleventy-img-helper is an Eleventy plugin that makes use of the eleventy-img utility to generate responsive images in Eleventy HTML output, regardless of the template language used. It takes the same options as eleventy-img, but with a few extras:

Installation

npm install --save-dev eleventy-img-helper

Usage

Add the plugin to your .eleventy.js:

const imgOptPlugin = require("eleventy-img-helper");

module.exports = function (eleventyConfig) {
const imgOptConfig = {
...configuration goes here
}
eleventyConfig.addPlugin(imgOptPlugin, imgOptConfig);
}

A complex configuration example (with a few notes)

const imgOptConfig = {
formats: ["avif", "webp", "jpeg"],
hashLength: 4,
filenameFormat: (id, src, width, format) => {
let filename = path.basename(src, path.extname(src)).split("-")[0];
return `${filename}-${id}-${width}.${format}`
},
sharpAvifOptions: { //supports all of the options in eleventy-img, even the niche ones
quality: 75
},
selectors: {
".headerImg": { //use any selector, as long as it matches <img> tags (doesn't have to explicitly specify them)
widths: [720, 1440, 2160],
sizes: "100vw",
htmlFunction: (metadata, options, attributes) => { //custom HTML tag generation
let newImgAttrs = {
src: metadata.jpeg[0].url,
loading: "lazy",
decoding: "async"
};
return `<picture>
${Object.values(metadata).map(imageFormat => {
return `<source
type="
${imageFormat[0].sourceType}"
srcset="
${imageFormat.map(entry => entry.srcset).join(", ")}"
sizes="
${options.sizes}">`
;
}).join("\n")}

<img
${Object.entries({...attributes, ...newImgAttrs}).map(attr => `${attr[0]}="${attr[1]}"`).join(" ")}>
</picture>
`
;
}
},
"article img": {
widths: [720, 1080],
sizes: "(min-width: 744px) 720px, 100vw"
},
"img[data-nl]": {
formats: ["webp", "png"], //overriding global format option above
sharpWebpOptions: {
nearLossless: true,
quality: 50
},
}
},
postFunction: (inputContent) => { //optional post function, HTML minification in this case
if (process.env.NODE_ENV === "prod") {
return htmlmin.minify(inputContent, {
useShortDoctype: true,
removeComments: true,
collapseWhitespace: true
})
}
return inputContent;
}
};

Links

More information about this project is available at the following locations:

This site has been updated. Click here or reload the page to update.