npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

posthtml-responsive-images

v1.0.3

Published

PostHTML plugin which generates 'srcset' and 'sizes' attributes according to configured presets

Downloads

6

Readme

posthtml-responsive-images

This is a PostHTML plugin which generates srcset and sizes attributes for images based on configured presets. It will just generate the HTML, not the actual images - but there are other tools for that. This plugin integrates especially well with ParcelJS.

The plugin requires the image element to have a width and height attribute matching the actual image dimensions - it will not try to resolve the image file and read its dimensions.

The plugin works with the following elements:

  • <img>
  • <source> inside a <picture>

Installation

npm i -D posthtml-responsive-images

Configuration

.posthtmlrc:

{
  "plugins": {
    "posthtml-responsive-images": {
      "urlFormat": "{baseUrl}{basename}@{width}x{height}.{ext}",
      "presets": {
        "preset A": {
          "sources": [ 128, 256, 512 ],
          "sizes": [
            [ 560, "256px" ],
            [ "30vw" ]
          ],
          "aspectRatio": "1:1"
        }
      }
    }
  }
}

HTML input

<img src="/images/thumbs/my-pretty-face.jpg" width="720" height="640" responsive="preset A">

HTML output

<img src="/images/thumbs/[email protected]"
  width="512"
  height="512"
  srcset="
    /images/thumbs/[email protected] 128w,
    /images/thumbs/[email protected] 256w,
    /images/thumbs/[email protected] 512w
  "
  sizes="(min-width: 560px) 256px, 30vw">

Configuration options

Global

| Option | Type | Description | |----------------|--------------------------|-----------------------------------------------------------------------------------| | urlFormat | string | Format string for generated URLs, see below for details. | | srcUrlFormat | string | Format string for adjusted src, see below for details. Defaults to urlFormat. | | presets | Record<string, Preset> | See next section. |

Presets

| Option | Type | Description | |----------------|---------------------------------------------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| | sources | number[] | An array of source sizes in ascending order. | | sizes | ([number, string / number] / string / number)[] | CSS sizes the image can have. If this is omitted, the sizes attribute will not be generated. All but the last entry should be a [number, string / number] tuple, where the first element represents the min-width of the viewport for the size to apply. The last entry is the default size. A size specified as a number will be suffixed with px. A size string which contains any of the characters -+*/() and doesn't begin with calc, clamp, max or min will be wrapped in a calc(). | | aspectRatio | string / number | Optional aspect ratio. If not specified, it will be calculated from the image width and height attributes. If this is specified, the height parameter of the generated URLs will be computed from the respective width using this aspect ratio. Can be specified as a fractional number (e.g. 0.5625 for 16:9) or a string formatted as either W:H or WxH. | | urlFormat | string | Optional preset-specific override for the global urlFormat option. | | srcUrlFormat | string | Optional preset-specific override for the global srcUrlFormat option. |

Generated output

The sources will be filtered to only use source sizes smaller than or equal to the original image width, so you're never enlarging small images.

Aside from generating the srcset and sizes attributes, the plugin will also adjust the src, width and height attributes to match the largest of the configured sizes which is still smaller than or equal to the original width. This means that if you set an aspectRatio, the width and height will now match that, and browsers which don't support srcset and sizes will gracefully fall back to the best resolution which should be needed for that particular image, no matter the source resolution.

The urlFormat and srcUrlFormat strings should include placeholders which will be replaced with the appropriate values. The available placeholders are:

| Placeholder | Value | |--------------|----------------------------------------------------------------------------------------------------------------------------------------------| | {baseurl} | The base URL of the image, that is, everything up to and including the last / character in the original image URL, e.g. /images/thumbs/. | | {filename} | The original image file name and extension, e.g. my-pretty-face.jpg. | | {basename} | The original image file name without extension, e.g. my-pretty-face. | | {ext} | The original image extension, e.g. jpg. | | {width} | The width of the image at the requested size. | | {height} | The height of the image at the requested size. |

Programmatic usage

The plugin exports the core generateResponsiveAttributes function, so if you have some special use-case which the plugin doesn't cover, you should be able to create your own plugin easily enough. The function has the following signature:

export function generateResponsiveAttributes(
  originalSrc: string,
  originalWidth: number,
  originalHeight: number,
  preset: ResponsiveImagePreset,
): ResponsiveAttributes;

The returned value is an object with the src, width, height, srcset, and optional sizes properties. The ResponsiveImagePreset type conforms to what is described in the Configuration section, but it should have its urlFormat already resolved to a string.