Skip to content

Commit

Permalink
Add support for full URLs in image plugin.
Browse files Browse the repository at this point in the history
  • Loading branch information
zachleat committed Jan 13, 2024
1 parent d78b03a commit e8a7253
Showing 1 changed file with 24 additions and 7 deletions.
31 changes: 24 additions & 7 deletions eleventy.config.images.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,38 @@
const path = require("path");
const eleventyImage = require("@11ty/eleventy-img");

module.exports = 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;
}
}

module.exports = 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.
Expand All @@ -29,6 +45,7 @@ module.exports = eleventyConfig => {
loading: "lazy",
decoding: "async",
};

return eleventyImage.generateHTML(metadata, imageAttributes);
});
};

0 comments on commit e8a7253

Please sign in to comment.