Mermaid support with theme switching for VitePress 2 #4999
nicolas-goudry
started this conversation in
Show and tell
Replies: 0 comments
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
I wanted to share the solution I came up with for adding Mermaid diagram support to VitePress 2 with proper dark/light theme switching.
The Journey
I initially tried the
vitepress-plugin-mermaidplugin, but it's not compatible with VitePress 2 and hasn't been updated in over 3 years.I also looked at the
markdown-it-mermaidplugin, but I got an error when registering it with VitePress and it hasn't been updated in over 8 years.So I decided to build something from the ground up, in two pieces:
The Vue component also features some VitePress-related niceties:
I started with the
vue-mermaid-stringpackage, which worked well for basic functionality. However, I ran into issues:nanoid()(which uses timestamps) occasionally generated duplicate IDs, causing diagrams to render in the wrong containersHence, I decided to inspire myself from this component and implement a minimal solution using the Mermaid library directly.
Implementation
Directory structure
Markdown-it Plugin
This is the simplest piece of code. I was mainly inspired by the
snippetplugin from VitePress..vitepress/plugins/vitepress-mermaid/index.tsVue Component
This is the heart of the integration. I was mainly inspired by
vue-mermaid-string, and got some help from Claude Sonnet 4.5.Some key features are:
:key="theme": forces Vue to recreate the component when theme changes, ensuring mermaid re-renders with the correct themefixedHeight: captures the diagram height after first render to prevent content shifting during theme transitions.mermaid:has(> svg): CSS-only solution to hide the diagram source text until next diagram is fully rendered, preventing flash.vitepress/plugins/vitepress-mermaid/index.vueVitePress Config
.vitepress/config.mtsTheme Registration
.vitepress/theme/index.tsResult
Now I can use mermaid diagrams in markdown:
And they'll automatically switch themes with VitePress theme switching.
Overall, this was a fun exercise in building a minimal, focused solution. Sometimes it's better to use a library directly rather than wrapping it, especially when you need specific behavior like reactive theme switching.
Hope this helps others looking to add Mermaid support to VitePress!
Beta Was this translation helpful? Give feedback.
All reactions