@d2lang/d2

中文文档
0.1.34发布于 2026/09/08MPL-2.0TypeScriptESM + CJS零依赖构建来源已验证近 30 天下载 7.4万

D2.js is a wrapper around the WASM build of D2, the modern text-to-diagram language.

原始使用文档
文档目录22 节
  1. Features
  2. Installation
  3. Nightly
  4. Usage
  5. Basic Usage
  6. Imports
  7. API Reference
  8. new D2()
  9. compile(input: string | CompileRequest, options?: CompileOp…
  10. render(diagram: Diagram, options?: RenderOptions): Promise<…
  11. dispose(): Promise<void>
  12. CompileOptions
  13. RenderOptions
  14. CompileRequest
  15. CompileResponse
  16. Development
  17. Building from source
  18. Running the dev server
  19. Tests
  20. Publishing
  21. Contributing
  22. License

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.

For an example of usage, see https://play.d2lang.com, which is powered by d2.js and is open-source.

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 @d2lang/d2

# yarn
yarn add @d2lang/d2

# pnpm
pnpm add @d2lang/d2

# bun
bun add @d2lang/d2

@terrastruct/d2 remains available as a compatibility package and receives the same releases during the namespace transition. New installations should use @d2lang/d2.

Nightly

Use the @nightly tag to get the version that is built by daily CI on the master branch.

For example,

yarn add @d2lang/d2@nightly

Usage

D2.js uses webworkers to call a WASM file.

Basic Usage

// Same for Node or browser
import { D2 } from '@d2lang/d2';
// Or using a CDN
// import { D2 } from 'https://esm.sh/@d2lang/d2';

const d2 = new D2();

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

Configuring render options (see CompileOptions for all available options):

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

const d2 = new D2();

const result = await d2.compile('x -> y', {
    sketch: true,
});
const svg = await d2.render(result.diagram, result.renderOptions);

Imports

In order to support imports, a mapping of D2 file paths to their content can be passed to the compiler.

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

const d2 = new D2();

const fs = {
  "project.d2": "a: @import",
  "import.d2": "x: {shape: circle}",
}

const result = await d2.compile({
    fs,
    inputPath: "project.d2",
    options: {
        sketch: true
    }
});
const svg = await d2.render(result.diagram, result.renderOptions);

API Reference

new D2()

Creates a new D2 instance.

compile(input: string | CompileRequest, options?: CompileOptions): Promise<CompileResponse>

Compiles D2 markup into an intermediate representation. Pass options directly as the second argument, for example d2.compile('x -> y', { layout: 'tala' }). For an object input, input.options is optional and takes precedence over the second argument when both specify the same option.

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

Renders a compiled diagram to SVG.

dispose(): Promise<void>

Terminates the worker backing this D2 instance and rejects any pending operations. Call this when the instance is no longer needed so Node processes can exit and browser worker resources are released. Calling dispose() more than once is safe.

CompileOptions

All RenderOptions properties in addition to:

  • layout: Layout engine to use ('dagre' | 'elk' | 'tala') [default: 'dagre']
  • fontRegular A byte array containing .ttf file to use for the regular font. If none provided, Source Sans Pro Regular is used.
  • fontItalic A byte array containing .ttf file to use for the italic font. If none provided, Source Sans Pro Italic is used.
  • fontBold A byte array containing .ttf file to use for the bold font. If none provided, Source Sans Pro Bold is used.
  • fontSemibold A byte array containing .ttf file to use for the semibold font. If none provided, Source Sans Pro Semibold is used.

RenderOptions

  • sketch: Enable sketch mode [default: false]
  • themeID: Theme ID to use [default: 0]
  • darkThemeID: Theme ID to use when client is in dark mode
  • center: Center the SVG in the containing viewbox [default: false]
  • pad: Pixels padded around the rendered diagram [default: 100]
  • scale: Scale the output. E.g., 0.5 to halve the default size. The default will render SVG's that will fit to screen. Setting to 1 turns off SVG fitting to screen.
  • forceAppendix: Adds an appendix for tooltips and links [default: false]
  • target: Target board/s to render. If target ends with '', it will be rendered with all of its scenarios, steps, and layers. Otherwise, only the target board will be rendered. E.g. target: 'layers.x.*' to render layer 'x' with all of its children. Pass '' to render all scenarios, steps, and layers. By default, only the root board is rendered. Multi-board outputs are currently only supported for animated SVGs and so animateInterval must be set to a value greater than 0 when targeting multiple boards.
  • animateInterval: If given, multiple boards are packaged as 1 SVG which transitions through each board at the interval (in milliseconds).
  • salt: Add a salt value to ensure the output uses unique IDs. This is useful when generating multiple identical diagrams to be included in the same HTML doc, so that duplicate IDs do not cause invalid HTML. The salt value is a string that will be appended to IDs in the output.
  • noXMLTag: Omit XML tag (<?xml ...?>) from output SVG files. Useful when generating SVGs for direct HTML embedding.

CompileRequest

  • fs: A mapping of D2 file paths to their content
  • inputPath: The path of the entry D2 file [default: index]
  • options: Optional CompileOptions to pass to the compiler

CompileResponse

  • diagram: Diagram: Compiled D2 diagram
  • renderOptions: RenderOptions: Render options merged with configuration set in diagram
  • fs
  • graph

Development

D2.js development requires the Go version in the root go.mod, the Bun version in package.json, and Node.js 24 with npm. The integration tests use Node to check the installed npm package in both CommonJS and ESM applications.

Optional: For optimal WASM file size, also install binaryen:

# macOS
brew install binaryen

# Ubuntu/Debian
sudo apt-get install binaryen

Building from source

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

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

./make.sh build

Running the dev server

You can browse the examples by running the dev server:

./make.sh dev

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

Tests

./make.sh test

Publishing

TODO stable release publishing.

Nightly builds are automated by CI by running:

PUBLISH=1 ./make.sh build

Contributing

Contributions are welcome!

License

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

版本与发布记录

@d2lang/d2 共发布 2 个版本,首次发布于 2026/08/08;过去 12 个月发布了 2 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.1.34latest2026/09/082 个月前
0.1.332026/08/083 个月前

关于 @d2lang/d2 的常见问题

@d2lang/d2 是什么?

D2.js is a wrapper around the WASM build of D2, the modern text-to-diagram language.

如何安装 @d2lang/d2?

在项目目录运行 npm install @d2lang/d2,或使用 pnpm add / yarn add / bun add。

@d2lang/d2 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@d2lang/d2 支持 ESM 还是 CommonJS?

同时提供 ES Module 与 CommonJS 入口,import 和 require() 都可以使用,打包工具会自动选择合适的版本。

@d2lang/d2 可以商用吗?

@d2lang/d2 使用 MPL-2.0 许可。弱 Copyleft:可以商用,也可以和闭源代码一起使用;但如果分发时修改了 MPL 授权的文件,这些文件的修改需以 MPL 开源。以上为概括,不构成法律意见,请以许可原文为准。

@d2lang/d2 的下载量有多少?

根据 npm 官方下载统计,@d2lang/d2 在 2026/10/11 – 2026/11/09 这 30 天内被下载 73,799 次,日均约 2,460 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@d2lang/d2 还在维护吗?

最新版本 0.1.34 发布于 2026/09/08(2 个月前);至今共发布 2 个版本,其中过去 12 个月发布了 2 个;首次发布于 2026/08/08。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。