ts-graphviz

3.0.7 · active · verified Sun Apr 19

ts-graphviz is a TypeScript-first library designed to programmatically construct and render Graphviz DOT language graphs. It provides a type-safe API for defining complex graph structures, including nodes, edges, and subgraphs, with full attribute support. The current stable version is 3.0.7, which is part of a monorepo that sees regular patch and minor releases across its constituent packages like `@ts-graphviz/core`, `@ts-graphviz/react`, and `@ts-graphviz/adapter`. This library differentiates itself by leveraging TypeScript's strong typing to prevent common Graphviz syntax errors at compile-time and offering a clean, object-oriented API for graph construction, making it suitable for modern Node.js and browser environments, especially when integrated with frameworks like React.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to programmatically define a directed graph using `ts-graphviz` with nodes, edges, and a subgraph, then convert it to a DOT string and render it to a PNG image using the Graphviz CLI.

import { digraph, node, edge, toDot, render } from 'ts-graphviz';
import { writeFile } from 'fs/promises';

async function generateGraphImage() {
  const G = digraph('MyGraph', (g) => {
    const start = node('start', { shape: 'Mdiamond', label: 'Start' });
    const processA = node('processA', { label: 'Process A' });
    const processB = node('processB', { label: 'Process B' });
    const end = node('end', { shape: 'Msquare', label: 'End' });

    edge([start, processA], { label: 'Init' });
    edge([processA, processB], { label: 'Data Transfer' });
    edge([processB, end], { label: 'Completion', color: 'green' });

    g.subgraph('cluster_steps', (c) => {
      c.label = 'Workflow Steps';
      c.style = 'filled';
      c.color = 'lightgrey';
      c.addNode(processA, processB);
    });
    g.addNode(start, end);
  });

  const dotString = toDot(G);
  console.log('Generated DOT string:\n', dotString);

  try {
    // Ensure Graphviz CLI 'dot' is installed and available in your system's PATH.
    // e.g., on macOS: `brew install graphviz`
    // e.g., on Ubuntu: `sudo apt-get install graphviz`
    const imageBuffer = await render(G, { format: 'png' });
    await writeFile('workflow_graph.png', imageBuffer);
    console.log('Graph image successfully generated at workflow_graph.png');
  } catch (error) {
    console.error('Error rendering graph. Is Graphviz CLI installed and in PATH?', error);
    throw error;
  }
}

generateGraphImage();

view raw JSON →