Replacing astro-mermaid with Pele: Build-Time Mermaid SVGs
Replace client-side astro-mermaid with Pele to pre-render Mermaid diagrams as static SVGs at build time with 0KB client JS and instant theme switching.
You embed a few architecture diagrams into your blog posts using ````mermaid` blocks. When readers open the page, the article text appears immediately, but the diagram areas remain blank placeholders. A few seconds later, after the browser finishes downloading and executing megabytes of library code, the page violently jerks downwards (Cumulative Layout Shift) as the diagrams finally pop into view.
This jarring delay is typical when using client-side Mermaid rendering libraries like astro-mermaid. In this guide, we walk through replacing astro-mermaid entirely with Pele — a lightweight Mermaid compiler that turns diagrams into pure, themeable SVGs during static site generation (SSG), saving 100% of client-side diagram JavaScript.
The Problem: Client-Side Mermaid Overhead#
The standard astro-mermaid integration relies on a browser-side lifecycle:
- At build time: Astro converts Markdown ````mermaid
blocks into plain` HTML elements.
- At page load: The browser fetches the full
mermaid.jsbundle (2MB to 3MB uncompressed). - Execution: The client CPU runs complex layout engines (Dagre, Elk, D3) to parse the syntax and paint SVG elements into the DOM.
- Theme switching: Toggling between light and dark modes forces JavaScript to re-parse and redraw every diagram on the page from scratch.
[!WARNING] If a reader has JavaScript disabled, uses a privacy extension that blocks heavy scripts, or suffers from high latency, client-side diagrams fail completely, leaving behind raw code blocks.
What is Pele? (Explain Like I’m 10)#
Think of it like buying a dinner table:
- Client-side Mermaid is like flat-pack furniture shipped with 100 loose screws and an instruction booklet: The customer (the reader’s browser) has to build the table before they can eat dinner.
- Pele is like having the craftsman build and finish the solid wood table before delivering it: As soon as the package arrives, the table is completely ready to use with zero assembly required.
Pele ↗ is an open-source Mermaid renderer created by kepano (CEO of Obsidian). Key benefits include:
- Synchronous Server-Side Rendering: Transforms Mermaid syntax into SVG directly inside Node.js or Bun without requiring a headless browser (such as Puppeteer).
- CSS Variable Theming: Pele SVGs rely on standard CSS custom properties like
--pele-bg,--pele-fg,--pele-surface, and--pele-border. Dark and light mode switches occur natively in CSS with zero runtime JavaScript. - Wide Syntax Compatibility: Seamlessly renders standard flowcharts, sequence diagrams, class diagrams, state diagrams, ER diagrams, git graphs, mindmaps, and timelines.
Step-by-Step Implementation Guide#
Step 1: Install Pele#
Add pele to your project dependencies:
bun add pele
# Or with npm: npm install pele
# Or with pnpm: pnpm add pelebashStep 2: Create the remark-pele.ts Plugin#
Create a new file at src/plugins/remark-pele.ts. This plugin traverses the Markdown Abstract Syntax Tree (MDAST), finds code blocks tagged with mermaid, and transforms them into inline SVG markup:
import type { Code, Root } from 'mdast';
import { render, type RenderOptions } from 'pele';
import { visit } from 'unist-util-visit';
export interface RemarkPeleOptions {
fontSize?: number;
fontFamily?: string;
renderOptions?: RenderOptions;
}
function escapeHtml(str: string): string {
return str
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/"/g, '"')
.replace(/'/g, ''');
}
export default function remarkPele(options: RemarkPeleOptions = {}) {
const defaultFontSize = options.fontSize ?? 14;
const defaultFontFamily = options.fontFamily ?? 'Inter, system-ui, sans-serif';
return (tree: Root) => {
let diagramIndex = 0;
visit(tree, 'code', (node: Code, index, parent) => {
if (
node.lang &&
node.lang.trim().toLowerCase() === 'mermaid' &&
parent &&
typeof index === 'number'
) {
try {
diagramIndex++;
const idPrefix = `pele-${diagramIndex}-`;
const { svg } = render(node.value, {
idPrefix,
responsive: true,
fontSize: defaultFontSize,
fontFamily: defaultFontFamily,
...options.renderOptions,
});
// Replace markdown code block with rendered SVG container
parent.children[index] = {
type: 'html',
value: `<div class="pele-diagram my-6 flex justify-center overflow-x-auto">${svg}</div>`,
};
} catch (err: unknown) {
const error = err as Error;
console.warn(`[remark-pele] Failed to render diagram:`, error?.message);
parent.children[index] = {
type: 'html',
value: `<div class="pele-error my-4 rounded-lg border border-red-500/50 bg-red-500/10 p-4"><p class="mb-2 font-mono text-xs text-red-500">Mermaid Render Error: ${escapeHtml(error?.message || String(err))}</p><pre class="overflow-x-auto text-xs"><code>${escapeHtml(node.value)}</code></pre></div>`,
};
}
}
});
};
}ts[!TIP] Setting
idPrefix: pele-${diagramIndex}-ensures that arrow markers, gradients, and clip paths inside SVGs remain unique across the page, avoiding duplicate ID bugs when multiple diagrams exist in one article.
Step 3: Configure astro.config.ts#
Open astro.config.ts, remove the astroMermaid integration, and pass remarkPele into markdown.processor:
import { defineConfig } from 'astro/config';
import { unified } from '@astrojs/markdown-remark';
import remarkPele from './src/plugins/remark-pele.ts';
import astroMermaid from 'astro-mermaid';
export default defineConfig({
markdown: {
processor: unified({
remarkPlugins: [
remarkMath,
remarkPele,
],
rehypePlugins: [ /* ... */ ],
}),
},
integrations: [
astroMermaid({ /* ... */ }),
AstroPureIntegration(config),
],
});tsStep 4: Theme with CSS Variables#
Map Pele’s theme variables to your site’s existing design tokens in your global stylesheet:
:root {
/* Pele Mermaid theme tokens (Light mode) */
--pele-font: Inter, system-ui, -apple-system, sans-serif;
--pele-font-mono: monospace;
--pele-radius: var(--radius);
--pele-bg: transparent;
--pele-fg: hsl(var(--foreground));
--pele-muted: hsl(var(--muted-foreground));
--pele-line: hsl(var(--muted-foreground));
--pele-surface: hsl(var(--muted));
--pele-surface-alt: hsl(var(--card));
--pele-border: hsl(var(--border));
--pele-accent: hsl(var(--primary));
}
.dark,
[data-theme="dark"] {
/* Pele Mermaid theme tokens (Dark mode) */
--pele-bg: transparent;
--pele-fg: hsl(var(--foreground));
--pele-muted: hsl(var(--muted-foreground));
--pele-line: hsl(var(--muted-foreground));
--pele-surface: hsl(var(--muted));
--pele-surface-alt: hsl(var(--card));
--pele-border: hsl(var(--border));
--pele-accent: hsl(var(--primary));
}cssAdd horizontal scrolling styling for mobile responsiveness:
.pele-diagram {
margin-block: 1.75rem;
display: flex;
justify-content: center;
align-items: center;
overflow-x: auto;
-webkit-overflow-scrolling: touch;
border-radius: var(--radius, 0.5rem);
padding: 0.5rem;
}
.pele-diagram svg.pele {
max-width: 100%;
height: auto;
display: block;
}cssStep 5: Clean Up Client Scripts & Uninstall Packages#
Delete the browser initialization scripts (mermaid.run() or mermaid.initialize()) from your main layout (such as BaseLayout.astro). Then remove the obsolete dependencies:
bun remove astro-mermaid mermaidbashResults & Impact#
| Metric | Before (astro-mermaid) | After (pele) | Improvement |
|---|---|---|---|
| Client JS Payload | ~2.5 MB (mermaid bundle) | 0 KB | -100% |
| Cumulative Layout Shift (CLS) | Frequent noticeable shifts | 0 (None) | Rock Solid |
| No-JavaScript Support | Broken / unrendered text | Renders perfectly | Complete resilience |
| Theme Switching Delay | Laggy JavaScript redraw | Instant (CSS) | Fluid |
| Build Time | N/A | 845 diagrams in ~1.5s | Near instantaneous |
Conclusion#
Switching from client-side Mermaid rendering to build-time SVGs with Pele delivers instant page loads, eliminates cumulative layout shifts, and removes megabytes of unnecessary client JavaScript while maintaining full aesthetic control via CSS tokens.