11ty / eleventy-img

Utility to perform build-time image transformations.
https://www.11ty.dev/docs/plugins/image/
433 stars 53 forks source link

Option to process images dynamically on request instead of at build-time #223

Closed zachleat closed 2 months ago

zachleat commented 2 months ago

Making use of the new onRequest Dev Server feature: https://www.11ty.dev/docs/dev-server/#onrequest-for-request-time-processing

This will greatly improve development speed during --serve (for projects that don’t have processed images on disk, already pretty fast using the existing disk cache).

https://www.11ty.dev/docs/plugins/image/#disk-cache

zachleat commented 2 months ago

Compatible with Eleventy v3.0.0-alpha.7 or newer.

zachleat commented 2 months ago

This feature will be automatically enabled and require no additional configuration when:

If you aren’t using those methods, you can manually opt-in using the transformOnRequest option and the eleventyImageOnRequestDuringServePlugin plugin:

const Image = require("@11ty/eleventy-img");
const { eleventyImageOnRequestDuringServePlugin } = require("@11ty/eleventy-img");

module.exports = function(eleventyConfig) {
    eleventyConfig.addShortcode("image", async function (src, alt) {
        let metadata = await Image(src, {
            transformOnRequest: process.env.ELEVENTY_RUN_MODE === "serve",
        });

        let imageAttributes = {
            alt,
        };

        // You bet we throw an error on a missing alt (alt="" works okay)
        return Image.generateHTML(metadata, imageAttributes);
    });

    // Serve images on request
    eleventyConfig.addPlugin(eleventyImageOnRequestDuringServePlugin);
};
zachleat commented 2 months ago

Shipping with Image 5.0.0-beta.1