Arief's Blog

Create diagrams in Astro with D2

D2, which stands for Declarative Diagramming, is a language, library, and tool that turns text into beautiful diagrams.

For example, you can write a sequence diagram like this:

direction: right
foo -> bar {style.animated: true}

Which will be rendered by D2 into:

Diagram

Installation

To start using D2 in your Astro project, you need to install the following:

  1. Install the D2 CLI - read more
  2. Install astro-d2 package - npx astro add astro-d2

Voila! You can now create D2 diagrams from your .{md,mdx} files.

Please refer to the D2 official documentation for more information, examples, and tutorials.

Deployment

Basically, there are two ways to deploy your Astro project with D2 integration.

The first one is to have the D2 CLI binary in your deployment environment, because the build process will need the CLI to generate the diagrams.

The second one is to pre-generate the diagrams before deploying your project and disable the generation in the build process. This is useful if you cannot or do not want to have the D2 CLI binary in your deployment environment. To achieve this you need to update the d2 integration object in the astro.config.mjs file:

export default defineConfig({
  ...
  integrations: [
    d2({
      output: "diagrams",
      // Skip D2 generation when building for production
      skipGeneration: !!process.env["SKIP_D2_GENERATION"],
    }),
    ...
  ],
  ...
});

Then, before deploying your project, you need to generate the diagrams by running pnpm build and make sure the diagrams directory is included in the deployment.

D2 vs Mermaid

Another alternative for diagramming in Astro is Mermaid. However, I find D2 more straightforward and easier to integrate with Astro. Mermaid requires more dependencies to be installed and configured, which are rehype-mermaid and playwright, that also lead to more complex deployment process.