Rebuilding images

rehype-image-salt has the ability to rebuild the <img> tag.

rebype-image-salt registered as plugin in unified and nuxt-content can be used as follows:

  • Add attributes to <img> tags
  • Replace <img> to <nuxt-img> etc.

unified

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

const rebuild = async (source: string) => {
  const html = await unified()
    .use(remarkParse)
    .use(remarkToRehype)
    .use(imageSalt, { command: 'rebuild', rebuild: { /* options... */ } })
    .use(rehypeStringify)
    .freeze()
    .process(source)
  return String(html)
}

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

nuxt-content

nuxt.config.js
{
  content: {
    markdown: {
      rehypePlugins: [
        [
          "@hankei6km/rehype-image-salt",
          {
            baseURL: "https://.../",
            rebuild: {
              // options...
            },
          },
        ],
      ],
    },
  },
}

Options

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

command

  • Type:rebuild | embed
  • Default: rebuild

The mode when running as plugin. Set reuild when rebuilding.

baseURL

  • Type:string
  • Default: none

A base part of image URL to be rebuilt. It will be removed from the image URL after rebuilding.

rebuild.tagName

  • Type:string
  • Default:img

Using a tag name to rebuilding <img>

rebuild.keepBaseURL

  • Type:boolean
  • Default:false

Keep the baseURL part in the image URL when rebuilding. The default value will be switched to false when tagName is nuxt-image component(ie: nuxt-img ).

rebuild.baseAttrs

  • Type: string
  • Default: ``

Describe the default attributes.

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