Skip to content

minifyHtml utility

The minifyHtml utility is used to normalize and minify HTML strings. It replaces multiple whitespace characters (including newlines and tabs) with a single space and trims the resulting string.

Why is this needed?

VitePress uses Vue for hydration. If the HTML rendered by the server (SSR) doesn't exactly match the HTML generated by the client during hydration, Vue will throw a "Hydration completed but contains mismatches" error.

When creating custom sidebar templates using sidebarItemTemplate or sidebarGroupTemplate, whitespace in your template string (like newlines for readability) often causes these mismatches. Using minifyHtml ensures that the HTML string is consistent between server and client.

Usage

You can import minifyHtml from vitepress-openapi or vitepress-openapi/client.

ts
import { minifyHtml } from 'vitepress-openapi'

const html = minifyHtml(`
  <span class="OASidebarItem">
    <span class="badge">GET</span>
    <span class="text">My Operation</span>
  </span>
`)

// Result: '<span class="OASidebarItem"> <span class="badge">GET</span> <span class="text">My Operation</span> </span>'

Example in Sidebar Configuration

This utility is especially useful when defining custom templates in your useSidebar configuration:

ts
import { useSidebar, minifyHtml } from 'vitepress-openapi'

const sidebar = useSidebar({
  spec,
  sidebarItemTemplate: ({ method, path, title }) => {
    const resolvedMethod = method.toUpperCase()
    const displayText = title || path
    
    return minifyHtml(`
      <span class="OASidebarItem">
        <span class="badge">${resolvedMethod}</span>
        <span class="text">${displayText}</span>
      </span>
    `)
  }
})