Embedding attributes of images

rehype-image-salt has a ability to embed attribute of <img> tag into alt or block.

It can be used to protect image attributes when converting HTML to Markdown.

unified

import { unified } from 'unified'
import rehypeParse from 'rehype-parse'
import rehypeToRemark from 'rehype-remark'
import stringify from 'remark-stringify'
import imageSalt from '@hankei6km/rehype-image-salt'

const embed = async (source: string) => {
  const markdown = await unified()
    .use(rehypeParse, { fragment: true })
    .use(imageSalt, { command: 'embed', embed: { embedTo: 'block' } })
    .use(rehypeToRemark)
    .use(remarkStringify)
    .freeze()
    .process(source)
  return String(markdown)
}

console.log(
  await embed(
    '<p><img src="/path/to/image.jpg" alt="river" width="600" height="400"></p>'
  )
) // ![river](/path/to/image.jpg){width="600" height="400"}

Options

The options is passed with the following objects. The behaviors of plugin is switched to embed multiple times by pass an array to the plugin.

command

  • Type:rebuild | embed
  • Default: rebuild

The mode when running as plugin. Set mebed when embedding.

baseURL

  • Type:string
  • Default: none

A base part of image URL to be embedded.

embed.embedTo

  • Type:alt | block
  • Default: alt

the destination to embed attributes.Embed to alt, Embed as block.

embed.pickAttrs

  • Type: string[]
  • Default: ['width', 'height']

A name of the attribute to embed.

Edit this page on GitHub Updated at Tue, Dec 21, 2021