How to integrate MermaidJs in Laravel Application

3 months ago

Hey everyone.

I have been using mermaid for a quite long time. Recently I feel interest to integrate mermaid in Laravel, but there is no good tutorial how can you connect Mermaid in your laravel application. Therefore I am planning to write this article.

What is mermaid?

Mermaid is a JavaScript library for generating diagrams and flowcharts from simple text-based descriptions. It allows you to create diagrams using a simple and intuitive syntax that can be easily embedded in Markdown documents, code comments, and other text-based formats.

With Mermaid, you can create a wide range of diagrams, including flowcharts, sequence diagrams, Gantt charts, class diagrams, and more. You simply write the diagram description using Mermaid syntax, and Mermaid generates a SVG or PNG image of the diagram.

Read more:

How to integrate?

There are few ways to integrate, but for pragmatism, I pull the CDN directly into my application, so that I can avoid some unnecessary steps.

So, I just place this code block in my template where normally I try to display the mermaid graph.

<script type="module">
    import mermaid from '[email protected]/dist/mermaid.esm.min.mjs';
        startOnLoad: true,
        theme: 'default'

Please take a note that mermaid.initialize({ startOnLoad: true, theme: 'default' }); initializes the Mermaid library with some configuration options. The startOnLoad option specifies that the Mermaid library should start generating diagrams as soon as the page is loaded. The theme option specifies the default theme to use for the diagrams. If you want to use different theme, you can choose whatever theme you want to use from there documentation:

How to use mermaid in your article?

I expect if I use mermaid graph like this way, it should work:

graph TB;
A --> B

Unfortunately it does not work. Therefore I choose a tricky solution for that. If I use <div> tag here, it should work.

graph TB; A --> B

Tweaking CSS (optional)

It you use any dark theme for markdown css, it might be overlapping with black background which does not looks good.

Therefore I just add extra css in my blade template.

pre.mermaid {
    background-color: white !important;

That's it. It should work as expected.

Feel free to share your comments. :)