The Problem
Mermaid diagrams in codebases tend to accumulate inconsistent formatting – misaligned indentation, irregular spacing around arrows, extra blank lines. When multiple developers edit the same diagrams, it gets worse.
Unlike code (which has Prettier, ESLint, gofmt), there was no dedicated formatter for Mermaid syntax.
The Solution
I built mermaid-formatter – a zero-dependency TypeScript tool that parses Mermaid diagrams into an AST and outputs clean, consistently formatted code.
Key features
-
Nested block indentation:
alt,loop,par,subgraphetc. are indented based on nesting depth -
Context-aware parsing:
elseis only treated as block control insidealt,andonly insidepar -
Arrow normalization:
A->>B:msg→A ->> B: msg(works across diagram types) - Markdown support: format all Mermaid code blocks in a Markdown file
-
CLI + library: use as
mermaidfmtcommand or importformatMermaid()in code
Quick start
npm install -g mermaid-formatter
# Format to stdout
mermaidfmt diagram.mmd
# Format in-place
mermaidfmt -w diagram.mmd
# Format from stdin
echo "sequenceDiagram
A->>B: hello" | mermaidfmt
Links
- GitHub: https://github.com/chenyanchen/mermaid-formatter
- npm: https://www.npmjs.com/package/mermaid-formatter
Feedback welcome!
Top comments (1)
Update:
mermaid-formatternow ships with a Prettier plugin! You can format.mmdfiles and Mermaid code blocks in Markdown through Prettier.Setup:
Then
prettier --write "**/*.mmd"andprettier --write "**/*.md"just work. Mermaid fenced code blocks inside Markdown are formatted automatically.Details: GitHub