How to create Class diagram in MermaidJS

1. Install MermaidJS

You can install MermaidJS by including the MermaidJS library in your project or by installing it via npm.

npm i mermaid

2. Define the diagram

To create a class diagram, start the definition with classDiagram. Define each class with its attributes and methods inside curly braces, then connect classes with relationship arrows.

classDiagram
    class Animal {
        +String name
        +makeSound()
    }
    class Dog {
        +fetch()
    }
    Animal <|-- Dog
    class Owner {
        +String name
    }
    Owner "1" *-- "many" Dog : owns

In this example, Dog inherits from Animal (empty triangle arrow), and one Owner owns many Dog instances via composition (filled diamond arrow).

3. Relationship types

MermaidJS class diagrams support the standard UML relationship arrows:

RelationshipSyntaxMeaningPreview
InheritanceClassA <|-- ClassBClassB is a subclass of ClassA
CompositionClassA *-- ClassBClassB cannot exist without ClassA (owns, filled diamond)
AggregationClassA o-- ClassBClassB can exist independently of ClassA (has-a, empty diamond)
AssociationClassA --> ClassBClassA uses or references ClassB
DependencyClassA ..> ClassBClassA depends on ClassB (dashed arrow)

4. Visibility modifiers and multiplicity

Prefix attributes/methods with + (public), - (private), or # (protected). Add multiplicity labels like "1" or "many" next to a relationship, and an optional : label to name it, as shown in the Owner "1" *-- "many" Dog : owns line above.

5. Render the diagram

Once you have defined the diagram, you can render it on your webpage by including the MermaidJS library and calling the mermaid function with the diagram definition as a string. Here is an example of how to do this

<html>
  <head>
    <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
    <script>
      mermaid.initialize({
        startOnLoad: true
      });
    </script>
  </head>
  <body>
    <div class="mermaid">
      classDiagram
        class Animal {
          +String name
          +makeSound()
        }
        class Dog {
          +fetch()
        }
        Animal <|-- Dog
        class Owner {
          +String name
        }
        Owner "1" *-- "many" Dog : owns
    </div>
  </body>
</html>

You can use this MermaidJS Playground Link to explore that particular example.