unified

Project: rehypejs/rehype-picture

Package: rehype-picture@3.0.0

  1. Dependencies: 3·Dependents: 0
  2. rehype plugin to wrap images in pictures
  1. unified 145
  2. html 106
  3. rehype 71
  4. hast 59
  5. rehype-plugin 51
  6. image 12
  7. img 2

rehype-picture

Build Coverage Downloads Size Sponsors Backers Chat

rehype plugin to wrap images in pictures.

Install

npm:

npm install rehype-picture

Use

var unified = require('unified')
var report = require('vfile-reporter')
var parse = require('rehype-parse')
var stringify = require('rehype-stringify')
var picture = require('rehype-picture')

unified()
  .use(parse, {fragment: true})
  .use(picture, {
    jpg: {webp: 'image/webp'},
    png: {svg: 'image/svg+xml'}
  })
  .use(stringify)
  .process('<img src="cat.jpg">\n<img src="logo.png">', function(err, file) {
    console.error(report(err || file))
    console.log(String(file))
  })

Yields:

no issues found
<picture><source srcset="cat.webp" type="image/webp"><img src="cat.jpg"></picture>
<picture><source srcset="logo.svg" type="image/svg+xml"><img src="logo.png"></picture>

API

rehype().use(picture[, options])

Options is an object mapping extensions (without dot, .) to search for on <img> elements to “sources”. Sources are objects mapping replacement extensions (without dot, .) to mime types.

So, if the following options are given:

{
  jpg: {webp: 'image/webp'},
  png: {svg: 'image/svg+xml'}
}

…that means jpg and png are the searched for extensions, which when found are wrapped in <picture> elements. The values at those keys are the <source> elements inserted in the picture.

Security

Although this plugin should be safe to use, always be careful with user input. For example, it’s possible to hide JavaScript inside images (such as GIFs, WebPs, and SVGs). User provided images open you up to a cross-site scripting (XSS) attack.

Contribute

See contributing.md in rehypejs/.github for ways to get started. See support.md for ways to get help.

This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.

License

MIT © Titus Wormer