|
| 1 | +const path = require("path"); |
| 2 | +const eleventyImage = require("@11ty/eleventy-img"); |
| 3 | + |
| 4 | +function relativeToInputPath(inputPath, relativeFilePath) { |
| 5 | + let split = inputPath.split("/"); |
| 6 | + split.pop(); |
| 7 | + |
| 8 | + return path.resolve(split.join(path.sep), relativeFilePath); |
| 9 | + |
| 10 | +} |
| 11 | + |
| 12 | +function isFullUrl(url) { |
| 13 | + try { |
| 14 | + new URL(url); |
| 15 | + return true; |
| 16 | + } catch(e) { |
| 17 | + return false; |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +module.exports = function(eleventyConfig) { |
| 22 | + // Eleventy Image shortcode |
| 23 | + // https://www.11ty.dev/docs/plugins/image/ |
| 24 | + eleventyConfig.addAsyncShortcode("image", async function imageShortcode(src, alt, widths, sizes) { |
| 25 | + // Full list of formats here: https://www.11ty.dev/docs/plugins/image/#output-formats |
| 26 | + // Warning: Avif can be resource-intensive so take care! |
| 27 | + let formats = ["avif", "webp", "auto"]; |
| 28 | + let input; |
| 29 | + if(isFullUrl(src)) { |
| 30 | + input = src; |
| 31 | + } else { |
| 32 | + input = relativeToInputPath(this.page.inputPath, src); |
| 33 | + } |
| 34 | + |
| 35 | + let metadata = await eleventyImage(input, { |
| 36 | + widths: widths || ["900,600,300"], |
| 37 | + formats, |
| 38 | + outputDir: path.join(eleventyConfig.dir.output, "img"), // Advanced usage note: `eleventyConfig.dir` works here because we’re using addPlugin. |
| 39 | + }); |
| 40 | + |
| 41 | + // TODO loading=eager and fetchpriority=high |
| 42 | + let imageAttributes = { |
| 43 | + alt, |
| 44 | + sizes, |
| 45 | + loading: "lazy", |
| 46 | + decoding: "async", |
| 47 | + }; |
| 48 | + |
| 49 | + return eleventyImage.generateHTML(metadata, imageAttributes); |
| 50 | + }); |
| 51 | +}; |
0 commit comments