Giter Club home page Giter Club logo

eleventy-plugin-img2picture's Introduction

eleventy-plugin-img2picture

Eleventy plugin to replace <img> using <picture> with resized and optimized images.

This plugin is inspired by eleventy-plugin-local-respimg by Sam Richard.

Requires Node 14.15+.

Table of Contents

Features

Supported Image Formats

This plugin uses eleventy-img to optimize, and generate different sizes and formats of images. All formats supported by eleventy-img are supported by eleventy-plugin-img2picture.

Usage

Basic Usage

const img2picture = require("eleventy-plugin-img2picture");

module.exports = function (eleventyConfig) {
  eleventyConfig.addPlugin(img2picture, {
    // Should be same as Eleventy input folder set using `dir.input`.
    eleventyInputDir: ".",

    // Output folder for optimized images.
    imagesOutputDir: "_site",

    // URL prefix for images src URLS.
    // It should match with path suffix in `imagesOutputDir`.
    // Eg: imagesOutputDir with `_site/images` likely need urlPath as `/images/`
    urlPath: "",
  });
};

Recommended Usage

👋 It's recommended to use the plugin only on production builds (E.g.: $ ELEVENTY_ENV=production eleventy). The plugin works fine with basic usage. Just that, your Eleventy builds will be quite slow.

module.exports = function (eleventyConfig) {
  if (process.env.ELEVENTY_ENV === "production") {
    eleventyConfig.addPlugin(img2picture, {
      // Should be same as Eleventy input folder set using `dir.input`.
      eleventyInputDir: ".",

      // Output folder for optimized images.
      imagesOutputDir: "_site",

      // URL prefix for images src URLS.
      // It should match with path suffix in `imagesOutputDir`.
      // Eg: imagesOutputDir with `_site/images` likely need urlPath as `/images/`
      urlPath: "",
    });
  } else {
    // During development, copy the files to Eleventy's `dir.output`
    eleventyConfig.addPassthroughCopy("./images");
  }
};

Options

Name Type Default Description
eleventyInputDir string 🚨 Required

Eleventy input directory. Should be same as Eleventy’s dir.input.
imagesOutputDir string 🚨 Required

Output folder for optimized images.
urlPath string 🚨 Required

URL prefix for images src URLS. It should match with path suffix in imagesOutputDir. Eg: imagesOutputDir with _site/images likely need urlPath as /images/
extensions array ["jpg", "png", "jpeg", "svg"] File extensions to optmize.
formats array ["avif", "webp", "svg", "jpeg"] Formats to be generated.

⚠️ The tags are ordered based on the order of formats in this array. Keep most compatible format at the end.
sizes string "100vw" Default image sizes attribute
minWidth number 150 Minimum image width to be generated
maxWidth number 1500 Maximum image width to be generated
hoistImgClass boolean false Move class attribute on <img> element to enclosing <picture> element.
pictureClass string "" Class attribute for the newly created <picture> elements
widthStep number 150 Width increments between each generated image
fetchRemote boolean false Fetch, cache, and optimize remote images.
dryRun boolean false Don't generate image files. Only HTML tags are generated.
svgShortCircuit boolean | "size" "size" See Eleventy Image Documentation

ℹ️ What is SVG short circuiting?
svgCompressionSize undefined | "br" undefined See Eleventy Image Documentation
filenameFormat function filenameFormatter() Function used by eleventy-img to generate image filenames.
cacheOptions object {} Cache options passed to eleventy-cache-assets.
sharpOptions object {} Options passed to Sharp constructor.
sharpWebpOptions object {} Options passed to [Sharp image format converter] for webp(https://sharp.pixelplumbing.com/api-output#webp).
sharpPngOptions object {} Options passed to Sharp image format converter for png.
sharpJpegOptions object {} Options passed to Sharp image format converter for jpeg.
sharpAvifOptions object {} Options passed to Sharp image format converter for avif.

Remote images

Set fetchRemote: true in options to download, cache, and optimize remote images. fetchRemote is false by default. Use cacheOptions passed to eleventy-cache-assets to change cache settings like, cache duration, and path.

Attributes on <img>

  • sizes will be hoisted on <source> elements.
  • src, width, and height attributes will be replaced with corresponding values based on the optimized image.
  • All other attributes on <img> will be retained.

Ignore Images

Images with data-img2picture-ignore="true" or data-img2picture-ignore will be ignored by the plugin.

<img
  data-img2picture-ignore="true"
  src="/images/sunset-by-bruno-scramgnon.jpg"
  alt="Sunset"
/>

Specify widths on <img>

You can provide a comma separated list of widths using data-img2picture-widths. This will override default widths computed from config (minWidth, maxWidth, and widthStep) for a particular <img>.

<img
  data-img2picture-widths="200,400,600,800"
  src="/images/sunset-by-bruno-scramgnon.jpg"
  alt="Sunset"
/>

Specify class for enclosing <picture> tags through <img>

You can provide class attribute for the enclosing <picture> using data-img2picture-picture-class data attribute. This will override the class provided using pictureClass option.

<img
  data-img2picture-picture-class="w-full"
  src="/images/sunset-by-bruno-scramgnon.jpg"
  alt="Sunset"
/>

Disk Cache

Disk cache is a feature provided by the eleventy-img plugin. This plugin will skip unchanged, and already existing images in the output path. If you don't delete generated image between builds, you'll get faster builds. This sample project shows how to persist disk cache across Netlify builds.

Example

<img
  class="w-full"
  src="shapes.png"
  alt="Shapes"
  data-variant="bleed"
  loading="eager"
  decoding="auto"
/>

...will generate:

<picture class="w-full"
  ><source
    type="image/avif"
    srcset="
      shapes-150w.avif   150w,
      shapes-300w.avif   300w,
      shapes-450w.avif   450w,
      shapes-600w.avif   600w,
      shapes-750w.avif   750w,
      shapes-900w.avif   900w,
      shapes-1050w.avif 1050w,
      shapes-1200w.avif 1200w,
      shapes-1350w.avif 1350w
    "
    sizes="100vw" />
  <source
    type="image/webp"
    srcset="
      shapes-150w.webp   150w,
      shapes-300w.webp   300w,
      shapes-450w.webp   450w,
      shapes-600w.webp   600w,
      shapes-750w.webp   750w,
      shapes-900w.webp   900w,
      shapes-1050w.webp 1050w,
      shapes-1200w.webp 1200w,
      shapes-1350w.webp 1350w
    "
    sizes="100vw" />
  <source
    type="image/jpeg"
    srcset="
      shapes-150w.jpeg   150w,
      shapes-300w.jpeg   300w,
      shapes-450w.jpeg   450w,
      shapes-600w.jpeg   600w,
      shapes-750w.jpeg   750w,
      shapes-900w.jpeg   900w,
      shapes-1050w.jpeg 1050w,
      shapes-1200w.jpeg 1200w,
      shapes-1350w.jpeg 1350w
    "
    sizes="100vw" />
  <img
    src="shapes-150w.jpeg"
    width="1350"
    height="1350"
    alt="Shapes"
    data-variant="bleed"
    sizes="100vw"
    loading="eager"
    decoding="auto"
/></picture>

FAQs

How to pick the right sizes?

I highly recommend to use the magical respimagelint - Linter for Responsive Images by Martin Auswöger.

How is this plugin different from others?

Plugins like eleventy-plugin-respimg, and eleventy-plugin-images-responsiver utilizes shortcodes or attributes to optimize images. The eleventy-plugin-img2picture doesn't rely on shortcode. It optimizes all <img> matching the file extensions. You can exclude <img> using data attribute data-img2picture-ignore.

eleventy-plugin-img2picture's People

Contributors

saneef avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

Forkers

digizard

eleventy-plugin-img2picture's Issues

`TemplateWriterWriteError` when trying to use the plugin

Hello there. I'm having trouble making the plugin work.

I'm getting this error on the terminal:

TemplateWriterWriteError was thrown

ENOENT: no such file or directory, stat '/images/uploads/meBio.png'

The path exists and it's correct, so I don't get the error. I'm a self taught programmer and sometimes is very hard to understand why things don't work. (the project does not have a "src" folder)

Thank you for your time.

The code:

const img2picture = require("eleventy-plugin-img2picture");

module.exports:

cfg.addPlugin(img2picture, {

  eleventyInputDir: "//",
  imagesOutputDir: "_site",
  urlPath: "_site/images/",
  extensions: ["jpg", "png", "jpeg"],
  formats: ["webp", "jpeg"],
  sizes: "100vw",
  minWidth: 150, // Minimum width to resize an image to
  maxWidth: 700, // Maximum width to resize an image to
  widthStep: 150, // Width difference between each resized image
  fetchRemote: false, // When true, remote images are fetched, cached and optimized.
  dryRun: false, // When true, the optimized images are not generated. Only HTMLs are processed.

  // Function used by eleventy-img to generate image filenames
  filenameFormat: function (id, src, width, format) {
    const extension = path.extname(src);
    const name = path.basename(src, extension);

    return `${name}-${id}-${width}w.${format}`;
  },

  cacheOptions: {},
  sharpOptions: {},
  sharpWebpOptions: {},
  sharpPngOptions: {},
  sharpJpegOptions: {},
  sharpAvifOptions: {},

});

Remote images not being optimised

Hello :)

I think I've uncovered a bug whereby using images via https doesn't result in images being fetched, optimised and rendered in tags.

My config is as follows:

./src/config/plugins/image.js

module.exports = {
	eleventyInputDir: "./src",
	imagesOutputDir: "public/assets/images",
	urlPath: "/assets/images/",
	fetchRemote: true,
	minWidth: 50,
	maxWidth: 2000,
	hoistImgClass: true,
	widthStep: 200,
	sizes: "100vw",
	sharpAvifOptions: {
		quality: 95,
	},
	sharpWebpOptions: {
		quality: 95,
	},
	sharpJpegOptions: {
		quality: 95,
	},
};

I'm then using eleventy with a Shopify plugin to fetch images and render them in the form of cards, using a Nunjucks macro. I have tested this using just an image tag, and the same still applies. The macro is called like so:

pages/product-listing.html

{% from 'components/listed-product.html' import listedProduct %}
...
  <section class="plp-listing">
    <ul class="plp-listing__container">
      {% for product in shopify.products | reverse %}
        {{ listedProduct(
          product.images.nodes[0].src,
          product.title,
          "$" + product.variants.nodes[0].priceV2.amount | formatPrice,
          '',
          "/products/" + product.handle)
        }}
      {% endfor %}
    </ul>
  </section>

Then this listed-product macro is as follows

_includes/components/listed-product.html

{% macro listedProduct(src, name, price, styles, href) %}
  <li class="listed-product {{ styles }}">
    <img class="listed-product__image" src="{{ src }}" alt="{{ name }}">
    <p class="listed-product__title">{{ name }}</p>
    <p class="listed-product__price">
      {{ price }}
    </p>
    <a href="{{ href }}" class="listed-product__button">View Product</a>
  </li>
{% endmacro %}

Finally, the built HTML in /public is so:

  <li class="listed-product ">
    <img class="listed-product__image" src="https://cdn.shopify.com/s/files/1/0748/0872/1690/files/edit-9.jpg?v=1689013081" alt="Proverbs Woman">
    <p class="listed-product__title">Proverbs Woman</p>
    <p class="listed-product__price">
      $55.00
    </p>
    <a href="/products/proverbs-woman" class="listed-product__button">View Product</a>
  </li>

Let me know if you need anything further from me :)

Applying Sharp placeholder

Hello, I want to apply a sharp placeholder to the images generated by this plugin.

See this issue for the specific placeholder manipulation that we are after.
lovell/sharp#1532

Is it possible to apply existing sharp placeholder options to this plugin or will an external library be required?

Thanks,

Make moving classes to picture tag optional

According to MDN (https://developer.mozilla.org/en-US/docs/Web/HTML/Element/picture)

The <img> element serves two purposes:

It describes the size and other attributes of the image and its presentation.
It provides a fallback in case none of the offered <source> elements are able to provide a usable image.

the <img> tag within a <picture> tag is still used to display whichever source is selected by the browser. Because of this the classes should still be on the <img> tag for full "styleability" or there should be a flag enabling the user to keep classes on the <img> tag.

In my case I am unable to achieve the same styling effect using Tailwind classes on an image using img2picture that I previously could but when I manually move the classes to the <img> tag with developer tools it works.

Another reason to do this is that in the case of a browser compatibility issue with <picture>, the <img> will still have styling.

Plugin messes with markup when `<body>` attribute names have special characters

I've attached a zip archive of a test project to demonstrate this issue. If you comment-out the plugin in .eleventy.js and run yarn start, the html is generated fully but no images generated (obviously). If you enable the img2picture config again in .eleventy.js the plugin does its thing, generates images, but the only thing in the html file is the picture - layouts/base.njk is not included in the resulting index.html file. As far as I can tell I have configured the plugin correctly. What is it that it does not like about my sample config?

const img2picture = require("eleventy-plugin-img2picture");

module.exports = config => {
    config.addPlugin(img2picture, {
        eleventyInputDir: "./src",
        imagesOutputDir: "./dist/images/processed",
        urlPath: "/images/processed",
        filenameFormat: function (id, src, width, format, options) {
            return `${id}-${width}.${format}`;
        }
    });

    return {
        templateFormats: ["md", "njk", "html"],
        markdownTemplateEngine: 'njk',
        dataTemplateEngine: 'njk',
        htmlTemplateEngine: 'njk',
        dir: {
            input: './src',
            output: './dist',
            includes: "_includes"
        }
    };
};

img2picture-test.zip

caching generated images

Hey Saneef,

hope addressing and discussing that here on GitHub is the right place.

If I do understand that right - from the README.md and from playing around with the options, the option "cacheOptions" is for specifying settings for the cache related to the fetch option - so to cache fetched remote images.

It is NOT - please correct me if I am wrong and tell me, what I have not seen or understood - to cache the images generated via the plugin.

Is a functionality like that planned or on the roadmap?

Because I think it would be a very good thing regarding to energy usage (climate), build minute budgets (small organizations) and so on.

Happy to read your thoughts about that. :)

Can't not have an alt text

Hello!

First off - amazing plugin. No other gives such fine-grained control over the image output while also being so easy to use.

However, the only thing I haven't been able to do is to pass a value on the img tag to get an alt="" to render.

There are some valid reasons for this - decorative or background images don't need alt text. I've tried passing alt="", alt=" " and looked through the docs for a data- attribute, but all methods still give me validation errors.

Ideally, I'd be able to use a data- attribute or pass alt="" and have alt="" returned (the latter returns alt on it's own, which Google doesn't like).

Let me know if I can provide more info :)

Does not work for output directories not named "_site"

When using imagesOutputDir option, the plugin will still export all images into _site in project root. My output directory, defined by eleventy is .www and when I set this as my image settings:

imagesOutputDir: ".www/static",

The images are still exported to _site.

Is this the nature of the plugin or am I missing something along the way?

Add possibility to preload responsive images using data-img2picture-preload

Hello :)

Was wondering if it was possible to create a responsive preload tag based on the presence of some attribute on tags, such as data-img2picture-preload

I've seen how this can be done here:
https://web.dev/articles/preload-responsive-images

The issue is, that with the default way of naming images, the hash at the end of the image isn't guaranteed, and creating a responsive preload with these randomly generated hashes is difficult.

I could change the filenameFormatter option to use a more predictable filename, but this prevents the eleventy-img disk cache:
https://www.11ty.dev/docs/plugins/image/#disk-cache

Therefore, would it be possible to "map" the srcset/sizes attribute from the tag, create a responsive preload, and add that to the of the associated html document, please?

I can try submitting a PR?

"no such file or directory" error when building

I have added this plugin to my project but I get an error when building it.

I've set it up according to the instructions and added it using:

eleventyConfig.addPlugin(img2picture, {
    eleventyInputDir: "", // Eleventy input folder.
    imagesOutputDir: "_site/assets/images/", // Output folder for optimized images.
    // URL prefix for images src URLS.
    // It should match with path suffix in `imagesOutputDir`.
    // Eg: imagesOutputDir with `_site/images` likely need urlPath as `/images/`
    urlPath: "/assets/images/",
    extensions: ["jpg", "png", "jpeg"],
    formats: ["avif", "webp", "jpeg"],
    sizes: "100vw",
    minWidth: 150,
    maxWidth: 1440,
    widthStep: 150,
    fetchRemote: false,
    dryRun: false,

    filenameFormat: function (id, src, width, format) {
      const extension = path.extname(src);
      const name = path.basename(src, extension);

      return `${name}-${id}-${width}w.${format}`;
    }
  });

The error I get is as follows:
https://pastebin.mozilla.org/WjARFvy6

All my images are placed in two places, just for testing. So they are in
assets/images/
and the output folder
_site/assets/images

I have tried setting the input and output directories to all kinds of values but I get the same error all the time.

What am I doing wrong?

AVIF size?

With that config i get:

     formats: ['avif', 'jpeg'],
      sharpAvifOptions: {
        lossless: true,
        quality: 10
      },
160K 17 Mar 01:54 _site/assets/images/blog/subsetter-kJ-yxM3qvS-1240w.avif
86K 17 Mar 01:54 _site/assets/images/blog/subsetter-kJ-yxM3qvS-1240w.jpeg
60K 17 Mar 01:54 _site/assets/images/blog/subsetter-kJ-yxM3qvS-640w.avif
33K 17 Mar 01:54 _site/assets/images/blog/subsetter-kJ-yxM3qvS-640w.jpeg

I think given the lossless and quality settings and output, it is not passed to sharp correctly.

When i use sharp cli it results in:

⚡ ⇒ npx sharp -i subsetter-kJ-yxM3qvS-1240w.jpeg -o optimized.avif -q 10 -f heif
10K 17 Mar 01:57 optimized.avif

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.