{"id":28194607,"url":"https://github.com/wernerglinka/metalsmith-optimize-images","last_synced_at":"2026-02-20T01:06:18.076Z","repository":{"id":293336559,"uuid":"983124643","full_name":"wernerglinka/metalsmith-optimize-images","owner":"wernerglinka","description":"Metalsmith plugin for generating responsive images with optimal formats","archived":false,"fork":false,"pushed_at":"2026-02-05T00:48:43.000Z","size":3429,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"main","last_synced_at":"2026-02-05T12:16:14.083Z","etag":null,"topics":["image-processing","metalsmith","metalsmith-plugin"],"latest_commit_sha":null,"homepage":"https://github.com/wernerglinka/metalsmith-optimize-images/tree/main","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/wernerglinka.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-05-13T23:17:23.000Z","updated_at":"2026-02-05T00:48:47.000Z","dependencies_parsed_at":null,"dependency_job_id":"c39e2c41-a669-4f4d-8003-69824be69ec3","html_url":"https://github.com/wernerglinka/metalsmith-optimize-images","commit_stats":null,"previous_names":["wernerglinka/metalsmith-optimize-images"],"tags_count":10,"template":false,"template_full_name":null,"purl":"pkg:github/wernerglinka/metalsmith-optimize-images","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wernerglinka%2Fmetalsmith-optimize-images","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wernerglinka%2Fmetalsmith-optimize-images/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wernerglinka%2Fmetalsmith-optimize-images/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wernerglinka%2Fmetalsmith-optimize-images/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/wernerglinka","download_url":"https://codeload.github.com/wernerglinka/metalsmith-optimize-images/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/wernerglinka%2Fmetalsmith-optimize-images/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":29637971,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-02-19T22:32:43.237Z","status":"ssl_error","status_checked_at":"2026-02-19T22:32:38.330Z","response_time":117,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.6:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["image-processing","metalsmith","metalsmith-plugin"],"created_at":"2025-05-16T13:12:26.252Z","updated_at":"2026-02-20T01:06:18.025Z","avatar_url":"https://github.com/wernerglinka.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# metalsmith-optimize-images\n\nMetalsmith plugin for generating responsive images with optimal formats\n\n[![metalsmith:plugin][metalsmith-badge]][metalsmith-url]\n[![npm: version][npm-badge]][npm-url]\n[![license: MIT][license-badge]][license-url]\n[![test coverage][coverage-badge]][coverage-url]\n[![ESM/CommonJS][modules-badge]][npm-url]\n[![Known Vulnerabilities](https://snyk.io/test/npm/metalsmith-optimize-images/badge.svg)](https://snyk.io/test/npm/metalsmith-optimize-images)\n\n\u003e This Metalsmith plugin is under active development. The API is stable, but breaking changes may occur before reaching 1.0.0.\n\n## Features\n\n- **Multiple image formats**: Generates AVIF and WebP variants with JPEG/PNG fallbacks\n- **Responsive sizes**: Creates different image sizes for various device widths\n- **Background image support**: Automatically processes unused images for CSS `image-set()` backgrounds\n- **Progressive loading**: Optional progressive image loading with low-quality placeholders\n- **Lazy loading**: Uses native browser lazy loading\n- **Content-based hashing**: Adds hash to filenames for optimal caching\n- **Layout shift prevention**: Adds width/height attributes\n- **Parallel processing**: Processes images in parallel\n- **Metadata generation**: Creates a JSON manifest with image information and variants\n- **Configurable compression**: Customize compression settings per format\n- **ESM and CommonJS support**:\n  - ESM: `import optimizeImages from 'metalsmith-optimize-images'`\n  - CommonJS: `const optimizeImages = require('metalsmith-optimize-images')`\n\n## Installation\n\n```bash\nnpm install metalsmith-optimize-images\n```\n\n## Usage\n\n\u003e This plugin **must** be run after assets are copied but before any final HTML processing.\n\n```javascript\nmetalsmith\n  .use(\n    assets({\n      source: 'lib/assets/', // Where to find assets\n      destination: 'assets/' // Where to copy assets\n    })\n  )\n  .use(\n    optimizeImages({\n      // configuration options\n      widths: [320, 640, 960, 1280, 1920],\n      formats: ['avif', 'webp', 'original']\n    })\n  );\n```\n\n## Options\n\n| Option                | Type       | Default                               | Description                                                                    |\n| --------------------- | ---------- | ------------------------------------- | ------------------------------------------------------------------------------ |\n| `widths`              | `number[]` | `[320, 640, 960, 1280, 1920]`         | Image sizes to generate                                                        |\n| `formats`             | `string[]` | `['avif', 'webp', 'original']`        | Image formats in order of preference                                           |\n| `formatOptions`       | `object`   | See below                             | Format-specific compression settings                                           |\n| `htmlPattern`         | `string`   | `**/*.html`                           | Glob pattern to match HTML files                                               |\n| `imgSelector`         | `string`   | `img:not([data-no-responsive])`       | CSS selector for images to process                                             |\n| `outputDir`           | `string`   | `assets/images/responsive`            | Where to store the responsive images                                           |\n| `outputPattern`       | `string`   | `[filename]-[width]w-[hash].[format]` | Filename pattern with tokens                                                   |\n| `skipLarger`          | `boolean`  | `true`                                | Don't upscale images                                                           |\n| `lazy`                | `boolean`  | `true`                                | Use native lazy loading                                                        |\n| `dimensionAttributes` | `boolean`  | `true`                                | Add width/height to prevent layout shift                                       |\n| `sizes`               | `string`   | `(max-width: 768px) 100vw, 75vw`      | Default sizes attribute                                                        |\n| `concurrency`         | `number`   | `5`                                   | Process N images at a time                                                     |\n| `generateMetadata`    | `boolean`  | `false`                               | Generate a metadata JSON file at `{outputDir}/responsive-images-manifest.json` |\n| `isProgressive`       | `boolean`  | `false`                               | Enable progressive image loading                                               |\n| `placeholder`         | `object`   | See below                             | Placeholder image settings                                                     |\n| `processUnusedImages` | `boolean`  | `true`                                | Process unused images for background use                                       |\n\n### Default Format Options\n\n```javascript\n{\n  avif: { quality: 65, speed: 5 },\n  webp: { quality: 80, lossless: false },\n  jpeg: { quality: 85, progressive: true },\n  png: { compressionLevel: 8, palette: true }\n}\n```\n\n### Default Placeholder Options\n\n```javascript\n{\n  width: 50,      // Width of placeholder image\n  quality: 30,    // Quality of placeholder image\n  blur: 10        // Blur amount for placeholder\n}\n```\n\n## How It Works\n\n### Standard Mode (default)\n\nThe plugin operates in two phases:\n\n**Phase 1: HTML-Referenced Images**\n\n1. Scans HTML files for image tags\n2. Processes each image to create multiple sizes and formats\n3. Creates a content hash for each image for efficient caching\n4. Replaces `\u003cimg\u003e` tags with responsive `\u003cpicture\u003e` elements\n5. Adds width/height attributes to prevent layout shifts\n6. Implements native lazy loading for better performance\n\n**Phase 2: Background Images (when `processUnusedImages: true`)**\n\n1. Finds images that weren't processed in Phase 1\n2. Generates 1x/2x variants (half size and original size) for retina displays\n3. Creates all configured formats (AVIF, WebP, original)\n4. Suitable for use with CSS `image-set()` for background images\n\n### Progressive Mode (experimental)\n\nWhen `isProgressive: true` is enabled:\n\n1. Generates low-quality placeholder images (small, blurred)\n2. Creates wrapper elements with both placeholder and high-resolution images\n3. Uses Intersection Observer to load high-resolution images on demand\n4. Implements smooth transitions between placeholder and final image\n5. Uses modern `createImageBitmap()` for reliable format detection (AVIF/WebP support)\n6. Maintains proper aspect ratios using original image dimensions\n7. Provides CSS and JavaScript for progressive loading behavior\n\n## Examples\n\n### Basic usage with defaults\n\n```javascript\nmetalsmith.use(optimizeImages());\n```\n\n### Custom configuration\n\n```javascript\nmetalsmith.use(\n  optimizeImages({\n    // Generate fewer sizes\n    widths: [480, 960, 1920],\n\n    // Only use WebP and original format\n    formats: ['webp', 'original'],\n\n    // Custom quality settings\n    formatOptions: {\n      webp: { quality: 75, lossless: false },\n      jpeg: { quality: 80, progressive: true }\n    },\n\n    // Custom selector for specific images\n    imgSelector: 'img.responsive',\n\n    // Custom output directory\n    outputDir: 'images/processed',\n\n    // Generate metadata manifest\n    generateMetadata: true, // Creates images/processed/responsive-images-manifest.json\n\n    // Don't add lazy loading\n    lazy: false\n  })\n);\n```\n\n### Progressive loading configuration\n\n```javascript\nmetalsmith.use(\n  optimizeImages({\n    // Enable progressive loading\n    isProgressive: true,\n\n    // Customize placeholder settings\n    placeholder: {\n      width: 40, // Smaller placeholder\n      quality: 20, // Lower quality for faster loading\n      blur: 15 // More blur for artistic effect\n    },\n\n    // Progressive mode works best with original format only\n    formats: ['original']\n  })\n);\n```\n\n### Excluding specific images\n\nAdd the `data-no-responsive` attribute to any image you don't want processed:\n\n```html\n\u003cimg src=\"image.jpg\" data-no-responsive alt=\"This image won't be processed\" /\u003e\n```\n\n## Supported File Types\n\nThe plugin automatically processes raster images and skips vector graphics:\n\n### ✅ Processed\n- **JPEG** (`.jpg`, `.jpeg`)\n- **PNG** (`.png`)\n- **GIF** (`.gif`)\n- **WebP** (`.webp`)\n- **AVIF** (`.avif`)\n\n### ❌ Automatically Skipped\n- **SVG** (`.svg`) - Vector graphics don't need responsive raster variants\n- **External URLs** (http/https)\n- **Data URLs** (`data:image/...`)\n- **Images with `data-no-responsive` attribute**\n\n### Why SVGs are skipped\n\nSVG files are vector graphics that scale perfectly at any resolution without quality loss. Creating multiple raster sizes and formats from SVGs would:\n- Increase build time unnecessarily\n- Generate larger file sizes than the original vector\n- Lose the scalability benefits of SVG format\n\nIf you have SVG logos or icons, they will remain untouched and work perfectly as-is.\n\n## Background Images\n\nThe plugin automatically processes images that aren't referenced in HTML for use as CSS background images. This feature is enabled by default (`processUnusedImages: true`).\n\n### How Background Processing Works\n\nAfter processing HTML-referenced images, the plugin:\n\n1. **Scans the Metalsmith files object** for all images\n2. **Excludes already-processed images** (those found during HTML scanning)\n3. **Excludes responsive variants** (generated images in the outputDir)\n4. **Generates 1x/2x variants** using actual image dimensions:\n   - **1x variant**: Half the original size for regular displays\n   - **2x variant**: Original image size for retina displays (sharper on high-DPI screens)\n5. **Creates all formats** (AVIF, WebP, original) for optimal browser support\n\n### Using Background Images with CSS\n\nFor an image like `images/hero.jpg` (1920x1080 pixels), the plugin generates variants like:\n\n```\nassets/images/responsive/hero-960w.avif   (1x - half 960px width for regular displays)\nassets/images/responsive/hero-1920w.avif  (2x - original 1920px width, sharper on retina)\nassets/images/responsive/hero-960w.webp   (1x - half 960px width for regular displays)\nassets/images/responsive/hero-1920w.webp  (2x - original 1920px width, sharper on retina)\nassets/images/responsive/hero-960w.jpg    (1x - half 960px width for regular displays)\nassets/images/responsive/hero-1920w.jpg   (2x - original 1920px width, sharper on retina)\n```\n\n**Note**: Background images are generated **without hashes** for easier CSS authoring. HTML images still include hashes for cache-busting.\n\nUse them in CSS with `image-set()`:\n\n```css\n.hero {\n  background-image: image-set(\n    url('/assets/images/responsive/hero-960w.avif') 1x,\n    url('/assets/images/responsive/hero-1920w.avif') 2x,\n    url('/assets/images/responsive/hero-960w.webp') 1x,\n    url('/assets/images/responsive/hero-1920w.webp') 2x,\n    url('/assets/images/responsive/hero-960w.jpg') 1x,\n    url('/assets/images/responsive/hero-1920w.jpg') 2x\n  );\n  background-size: cover;\n  background-position: center;\n}\n```\n\n### Background Image Configuration\n\n```javascript\nmetalsmith.use(\n  optimizeImages({\n    // Standard HTML image processing\n    widths: [320, 640, 960, 1280, 1920],\n    formats: ['avif', 'webp', 'original'],\n\n    // Background image processing\n    processUnusedImages: true, // Enable background processing\n\n    // Generate metadata to see all variants\n    generateMetadata: true\n  })\n);\n```\n\n### Benefits of Background Image Processing\n\n- **Automatic format optimization** - Browser selects best supported format\n- **Retina display support** - 2x variants provide crisp images on high-DPI screens\n- **No manual work** - Plugin automatically finds and processes unused images in Metalsmith files object\n- **Consistent workflow** - Same formats and quality settings as HTML images\n\n## Progressive Loading\n\n### Overview\n\nProgressive loading provides a smooth user experience by:\n\n1. **Immediate display**: Shows a low-quality placeholder instantly\n2. **Smooth transitions**: Fades from placeholder to high-quality image\n3. **Lazy loading**: Only loads high-resolution images when they enter the viewport\n4. **Format optimization**: Automatically serves the best supported format\n\n### Implementation\n\nWhen progressive mode is enabled, the plugin:\n\n- Generates small, blurred placeholder images\n- Creates wrapper elements with proper aspect ratios\n- Includes JavaScript for intersection observer-based loading\n- Provides CSS for smooth transitions\n\n### HTML Output\n\n**Standard mode:**\n\n```html\n\u003cpicture\u003e\n  \u003csource\n    type=\"image/avif\"\n    srcset=\"image-320w.avif 320w, image-640w.avif 640w\"\n    sizes=\"(max-width: 768px) 100vw, 75vw\"\n  /\u003e\n  \u003csource\n    type=\"image/webp\"\n    srcset=\"image-320w.webp 320w, image-640w.webp 640w\"\n    sizes=\"(max-width: 768px) 100vw, 75vw\"\n  /\u003e\n  \u003cimg\n    src=\"image-640w.jpg\"\n    srcset=\"image-320w.jpg 320w, image-640w.jpg 640w\"\n    sizes=\"(max-width: 768px) 100vw, 75vw\"\n    alt=\"Description\"\n    loading=\"lazy\"\n  /\u003e\n\u003c/picture\u003e\n```\n\n**Progressive mode:**\n\n```html\n\u003cdiv class=\"responsive-wrapper js-progressive-image-wrapper\" style=\"aspect-ratio: 1280/720\"\u003e\n  \u003cimg class=\"low-res\" src=\"/assets/images/responsive/image-placeholder.jpg\" alt=\"Description\" /\u003e\n  \u003cimg class=\"high-res\" src=\"\" alt=\"Description\" data-source=\"/assets/images/responsive/image-960w.jpg\" /\u003e\n\u003c/div\u003e\n```\n\n### CSS Requirements\n\nThe plugin provides CSS for progressive loading, but you can customize it:\n\n```css\n.responsive-wrapper {\n  position: relative;\n  overflow: hidden;\n  background-color: #f0f0f0;\n}\n\n.responsive-wrapper .low-res {\n  position: absolute;\n  top: 0;\n  left: 0;\n  width: 100%;\n  height: 100%;\n  object-fit: cover;\n  transition: opacity 0.4s ease;\n}\n\n.responsive-wrapper .high-res {\n  position: absolute;\n  top: 0;\n  left: 0;\n  width: 100%;\n  height: 100%;\n  object-fit: cover;\n  opacity: 0;\n  transition: opacity 0.4s ease;\n}\n\n.responsive-wrapper.done .high-res {\n  opacity: 1;\n}\n\n.responsive-wrapper.done .low-res {\n  opacity: 0;\n}\n```\n\n## Metadata Manifest\n\nWhen `generateMetadata: true` is enabled, the plugin creates a JSON file at `{outputDir}/responsive-images-manifest.json` containing detailed information about all processed images:\n\n```json\n{\n  \"images/hero.jpg\": [\n    {\n      \"path\": \"assets/images/responsive/hero-320w-a1b2c3d4.avif\",\n      \"width\": 320,\n      \"height\": 180,\n      \"format\": \"avif\",\n      \"size\": 8432\n    },\n    {\n      \"path\": \"assets/images/responsive/hero-320w-a1b2c3d4.webp\",\n      \"width\": 320,\n      \"height\": 180,\n      \"format\": \"webp\",\n      \"size\": 12658\n    }\n  ]\n}\n```\n\nThis manifest is useful for:\n\n- **Debugging**: Verify which variants were generated\n- **Integration**: Use variant information in other tools\n- **Performance analysis**: Compare file sizes across formats\n\n## Debug\n\nTo enable debug logs, set the DEBUG environment variable to metalsmith-optimize-images\\*:\n\n```javascript\nmetalsmith.env('DEBUG', 'metalsmith-optimize-images*');\n```\n\n## CLI Usage\n\n### Metalsmith CLI\n\n```json\n{\n  \"plugins\": {\n    \"metalsmith-optimize-images\": {\n      \"widths\": [320, 640, 960, 1280, 1920],\n      \"formats\": [\"avif\", \"webp\", \"original\"]\n    }\n  }\n}\n```\n\n## License\n\nMIT\n\n## Development transparency\n\nPortions of this project were developed with the assistance of AI tools including Claude and Claude Code. These tools were used to:\n\n- Generate or refactor code\n- Assist with documentation\n- Troubleshoot bugs and explore alternative approaches\n\nAll AI-assisted code has been reviewed and tested to ensure it meets project standards. See the included [CLAUDE.md](CLAUDE.md) file for more details.\n\n[npm-badge]: https://img.shields.io/npm/v/metalsmith-optimize-images.svg\n[npm-url]: https://www.npmjs.com/package/metalsmith-optimize-images\n[metalsmith-badge]: https://img.shields.io/badge/metalsmith-plugin-green.svg?longCache=true\n[metalsmith-url]: https://metalsmith.io\n[license-badge]: https://img.shields.io/github/license/wernerglinka/metalsmith-optimize-images\n[license-url]: LICENSE\n[coverage-badge]: https://img.shields.io/badge/test%20coverage-95%25-brightgreen\n[coverage-url]: https://github.com/wernerglinka/metalsmith-optimize-images/actions/workflows/test.yml\n[modules-badge]: https://img.shields.io/badge/modules-ESM%2FCJS-blue\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwernerglinka%2Fmetalsmith-optimize-images","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fwernerglinka%2Fmetalsmith-optimize-images","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fwernerglinka%2Fmetalsmith-optimize-images/lists"}