d2/d2js/js
Alexander Wang 45a9f58b42
fix example
2025-01-13 20:18:15 -07:00
..
ci fix build command 2025-01-12 11:13:10 -07:00
examples fix example 2025-01-13 20:18:15 -07:00
src cleanup 2025-01-13 11:04:48 -07:00
test separate node esm and browser esm builds 2025-01-12 21:36:19 -07:00
wasm init d2.js 2025-01-12 10:50:05 -07:00
.gitignore separate node esm and browser esm builds 2025-01-12 21:36:19 -07:00
build.js remove entrypoints and code split esm module 2025-01-13 19:38:27 -07:00
bun.lockb init d2.js 2025-01-12 10:50:05 -07:00
CHANGELOG.md init d2.js 2025-01-12 10:50:05 -07:00
dev-server.js init d2.js 2025-01-12 10:50:05 -07:00
make.sh init d2.js 2025-01-12 10:50:05 -07:00
Makefile cleanup stage 2025-01-13 11:03:30 -07:00
package.json fix example 2025-01-13 20:18:15 -07:00
README.md init d2.js 2025-01-12 10:50:05 -07:00

D2.js

npm version License: MPL-2.0

D2.js is a JavaScript wrapper around D2, the modern diagram scripting language. It enables running D2 directly in browsers and Node environments through WebAssembly.

Features

  • 🌐 Universal - Works in both browser and Node environments
  • 🚀 Modern - Built with ESM modules, with CJS fallback
  • 🔄 Isomorphic - Same API everywhere
  • Fast - Powered by WebAssembly for near-native performance
  • 📦 Lightweight - Minimal wrapper around the core D2 engine

Installation

# npm
npm install @terrastruct/d2

# yarn
yarn add @terrastruct/d2

# pnpm
pnpm add @terrastruct/d2

# bun
bun add @terrastruct/d2

Usage

Browser

import { D2 } from '@terrastruct/d2';

const d2 = new D2();

const result = await d2.compile('x -> y');
const svg = await d2.render(result.diagram);

const result = await d2.compile('x -> y', {
  layout: 'dagre',
  sketch: true
});

Node

import { D2 } from '@terrastruct/d2';

const d2 = new D2();

async function createDiagram() {
  const result = await d2.compile('x -> y');
  const svg = await d2.render(result.diagram);
  console.log(svg);
}

createDiagram();

API Reference

new D2()

Creates a new D2 instance.

compile(input: string, options?: CompileOptions): Promise<CompileResult>

Compiles D2 markup into an intermediate representation.

Options:

  • layout: Layout engine to use ('dagre' | 'elk') [default: 'dagre']
  • sketch: Enable sketch mode [default: false]

render(diagram: Diagram, options?: RenderOptions): Promise<string>

Renders a compiled diagram to SVG.

Development

D2.js uses Bun, so install this first.

Building from source

git clone https://github.com/terrastruct/d2.git
cd d2/d2js/js
./make.sh

If you change the main D2 source code, you should regenerate the WASM file:

./make.sh build

Running the Development Server

bun run dev

Visit http://localhost:3000 to see the example page.

Contributing

Contributions are welcome!

License

This project is licensed under the Mozilla Public License Version 2.0.