From ceebb3ad4459c85372a0a65af96ac02b64a9beb9 Mon Sep 17 00:00:00 2001 From: Zach Leatherman Date: Sun, 14 Jan 2024 12:35:07 +1300 Subject: [PATCH] Add support for full URLs in image plugin. --- eleventy.config.images.js | 31 ++++++++++++++++++++++++------- 1 file changed, 24 insertions(+), 7 deletions(-) diff --git a/eleventy.config.images.js b/eleventy.config.images.js index b2c98b2..67103fe 100644 --- a/eleventy.config.images.js +++ b/eleventy.config.images.js @@ -1,22 +1,38 @@ import path from "path"; import eleventyImage from "@11ty/eleventy-img"; -export default function(eleventyConfig) { - function relativeToInputPath(inputPath, relativeFilePath) { - let split = inputPath.split("/"); - split.pop(); +function relativeToInputPath(inputPath, relativeFilePath) { + let split = inputPath.split("/"); + split.pop(); - return path.resolve(split.join(path.sep), relativeFilePath); + return path.resolve(split.join(path.sep), relativeFilePath); + +} + +function isFullUrl(url) { + try { + new URL(url); + return true; + } catch(e) { + return false; } +} +export default function(eleventyConfig) { // Eleventy Image shortcode // https://www.11ty.dev/docs/plugins/image/ eleventyConfig.addAsyncShortcode("image", async function imageShortcode(src, alt, widths, sizes) { // Full list of formats here: https://www.11ty.dev/docs/plugins/image/#output-formats // Warning: Avif can be resource-intensive so take care! let formats = ["avif", "webp", "auto"]; - let file = relativeToInputPath(this.page.inputPath, src); - let metadata = await eleventyImage(file, { + let input; + if(isFullUrl(src)) { + input = src; + } else { + input = relativeToInputPath(this.page.inputPath, src); + } + + let metadata = await eleventyImage(input, { widths: widths || ["auto"], formats, outputDir: path.join(eleventyConfig.dir.output, "img"), // Advanced usage note: `eleventyConfig.dir` works here because we’re using addPlugin. @@ -29,6 +45,7 @@ export default function(eleventyConfig) { loading: "lazy", decoding: "async", }; + return eleventyImage.generateHTML(metadata, imageAttributes); }); };