From f8c0f147aa1f0e364c5e0abf55152a93733125b1 Mon Sep 17 00:00:00 2001 From: Claudia Reynders <> Date: Mon, 25 Apr 2022 21:06:47 +0200 Subject: [PATCH] Added v1 of image optimisation using the eleventy-img plugin --- .eleventy.js | 1 + src/_11ty/imageShortcode.js | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 36 insertions(+) create mode 100644 src/_11ty/imageShortcode.js diff --git a/.eleventy.js b/.eleventy.js index 6f16fba..805097e 100644 --- a/.eleventy.js +++ b/.eleventy.js @@ -4,6 +4,7 @@ module.exports = function(eleventyConfig) { eleventyConfig.addPlugin(eleventyNavigationPlugin) eleventyConfig.addLayoutAlias('page', 'layouts/page') + eleventyConfig.addNunjucksAsyncShortcode('image', require('./src/_11ty/imageShortcode').imageShortcode) /* Creating a collection of blogposts by filtering based on folder and filetype */ eleventyConfig.addCollection("blog", (collectionApi) => { diff --git a/src/_11ty/imageShortcode.js b/src/_11ty/imageShortcode.js new file mode 100644 index 0000000..cdc815f --- /dev/null +++ b/src/_11ty/imageShortcode.js @@ -0,0 +1,35 @@ +const Image = require("@11ty/eleventy-img") +const path = require('path') + +const imageShortcode = async ( + relativeSrc, + alt, + className, + widths = [null, 300, 800, 1280], + formats = ['webp'], + sizes = '(min-width: 100px)' +) => { + const { dir: imgDir } = path.parse(relativeSrc); + const fullSrc = path.join('src', relativeSrc); + + const imageMetadata = await Image(relativeSrc, { + widths, + formats, + outputDir: "./_site/assets/images/generated/", + urlPath: "/assets/images/generated/", + }) + + const imageAttributes = { + alt, + sizes, + loading: 'lazy', + decoding: 'async', + } + + if(className) {imageAttributes["class"] = className } + + return Image.generateHTML(imageMetadata, imageAttributes) +} + + +module.exports.imageShortcode = imageShortcode; \ No newline at end of file