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 🙏

© 2026 – Pkg Stats / Ryan Hefner

html-responsive-img

v1.0.0

Published

Transform HTML img tags to responsive picture elements or srcset attributes

Readme

html-responsive-img

Transform HTML img tags into responsive picture elements or srcset attributes with configurable transformation rules.

Features

  • 🖼️ Transform <img> tags to <picture> elements with multiple formats (AVIF, WebP, original)
  • 📱 Generate responsive srcset attributes for different screen sizes
  • 🎯 CSS selector-based targeting for precise transformations
  • 🔧 Flexible URL extraction and generation with templates
  • 🚀 Works in both Node.js and browser environments
  • ⚡ Fast HTML parsing and transformation
  • 🛠️ CLI tool for batch processing

Installation

npm install html-responsive-img

Quick Start

Node.js

import { responsify } from 'html-responsive-img';

const html = '<img src="https://example.com/photo.jpg" class="hero">';

const config = {
  transforms: [{
    selector: '.hero',
    extract: {
      pattern: /^(.+)\/([^\/]+)\.([^.]+)$/,
      groups: { basePath: 1, filename: 2, ext: 3 }
    },
    urlTemplate: '{basePath}/{filename}_{width}w.{format}',
    widths: [400, 800, 1200],
    formats: ['avif', 'webp', 'original'],
    type: 'picture'
  }]
};

const result = responsify(html, config);
console.log(result.html);
// Output: <picture>...</picture> with multiple source elements

CLI

# Transform a single file
responsify --input index.html --config config.json --output result.html

# Use with pipes
cat page.html | responsify --config config.json > output.html

# Output as JSON for inspection
responsify --input page.html --config config.json --format json

Configuration

Transform Configuration

Each transform rule in the config can have the following properties:

| Property | Type | Description | |----------|------|-------------| | selector | string | CSS selector to match images | | extract | object | URL extraction configuration | | urlTemplate | string | Template for generating new URLs | | widths | number[] | Array of widths to generate | | formats | string[] | Array of formats (e.g., 'avif', 'webp', 'original') | | type | 'picture' | 'srcset' | Output type | | sizes | string | Optional sizes attribute for responsive images | | loading | 'lazy' | 'eager' | Optional loading attribute |

URL Extraction

Extract URL components using regex patterns or custom functions:

// Regex pattern extraction
{
  extract: {
    pattern: /^(.+)\/([^\/]+)\.([^.]+)$/,
    groups: { basePath: 1, filename: 2, ext: 3 }
  }
}

// Custom extraction function
{
  extract: {
    custom: (url) => {
      // Custom logic to extract components
      return { basePath: '...', filename: '...', ext: '...' };
    }
  }
}

URL Templates

Use placeholders in URL templates that will be replaced with extracted values:

  • {basePath} - Base path from extraction
  • {filename} - Filename from extraction
  • {ext} - Original file extension
  • {format} - Current format being generated
  • {width} - Current width being generated

Example: {basePath}/{filename}_{width}w.{format}

API

responsify(html: string, config: Config): TransformResult

Synchronously transform HTML with the given configuration.

Returns:

{
  success: boolean;
  html?: string;        // Transformed HTML (if success)
  error?: string;       // Error message (if failed)
  stats?: {
    imagesFound: number;
    imagesTransformed: number;
    rulesApplied: number;
    processingTime: number;
  };
}

responsifyAsync(html: string, config: Config): Promise<TransformResult>

Asynchronously transform HTML (useful for large documents).

validateConfig(config: Config): ValidationResult

Validate a configuration object before use.

loadPreset(presetName: string): Config

Load a predefined configuration preset.

Available presets:

  • 'standard' - Common responsive image setup
  • 'cloudinary' - Cloudinary CDN optimized

Browser Usage

<script type="module">
  import { transformDocument } from 'html-responsive-img/browser';

  const config = { /* ... */ };
  transformDocument(config);
</script>

Examples

Picture Element with Multiple Formats

const config = {
  transforms: [{
    selector: 'img',
    extract: {
      pattern: /^(.+)\/([^\/]+)\.([^.]+)$/,
      groups: { basePath: 1, filename: 2, ext: 3 }
    },
    urlTemplate: '{basePath}/{filename}_{width}w.{format}',
    widths: [400, 800, 1200],
    formats: ['avif', 'webp', 'original'],
    type: 'picture'
  }]
};

Responsive Srcset

const config = {
  transforms: [{
    selector: '.responsive',
    extract: {
      pattern: /^(.+)\/([^\/]+)\.([^.]+)$/,
      groups: { basePath: 1, filename: 2, ext: 3 }
    },
    urlTemplate: '{basePath}/{filename}_{width}w.{ext}',
    widths: [320, 640, 1280],
    type: 'srcset',
    sizes: '(max-width: 640px) 100vw, 50vw'
  }]
};

Multiple Rules

const config = {
  transforms: [
    {
      selector: '.hero',
      // Hero image configuration
    },
    {
      selector: '.thumbnail',
      // Thumbnail configuration
    }
  ]
};

TypeScript

Full TypeScript support with type definitions included:

import { Config, TransformResult } from 'html-responsive-img';

const config: Config = {
  transforms: [/* ... */]
};

const result: TransformResult = responsify(html, config);

Performance

  • Efficient HTML parsing with minimal overhead
  • Batched transformations for multiple images
  • Streaming support for large documents
  • ~85 tests ensuring reliability

Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

License

MIT

Author

Created with ❤️ for modern responsive web development