文章摘要
D2是一种声明式图表脚本语言,可将文本转换为图表。用户只需描述所需图表内容,D2即可生成对应图像。例如通过编写D2脚本定义网络拓扑(如卫星、发射塔、用户等元素及其关系),配合命令行工具即可自动生成可视化图表,支持多种主题和布局引擎配置。
文章总结
D2 是一种将文本转换为图表的脚本语言,全称为声明式图表语言(Declarative Diagramming)。用户只需描述所需图表内容,系统即可自动生成对应图像。
例如,下载D2命令行工具后,创建一个名为input.d2的文件,复制以下代码并运行指定命令,即可生成下方图示:
```d2 vars: { d2-config: { layout-engine: elk theme-id: 300 } } network: { cell tower: { satellites: { shape: stored_data; style.multiple: true } transmitter satellites -> transmitter: send (重复3次) } online portal: { ui: {shape: hexagon} } data processor: { storage: {shape: cylinder; style.multiple: true} } cell tower.transmitter -> data processor.storage: phone logs }
user: { shape: person; width: 130 } user -> network.cell tower: make call user -> network.online portal.ui: access { style.stroke-dash: 3 }
api server -> network.online portal.ui: display api server -> logs: persist logs: {shape: page; style.multiple: true} network.data processor -> api server ```
实时预览功能:

本教程约需5-10分钟完成,文末提供可下载的速查表。如需快速入门,《基础指南》仅需2分钟。
提示:多数代码片段可悬停鼠标直接在Playground中调试(使用import语句的示例除外)。
评论总结
以下是评论内容的总结:
支持D2的观点: 1. D2比Mermaid更优秀,表达力更强: - "D2 has been around for a while... It's so much better than mermaid" (评论1) - "D2 is more expressive than Mermaid is a useful property when doing AI-aided diagram generation" (评论3)
- D2具有实用功能,如草图模式和交互工具:
- "It's got a sketch mode included!... Those two make a huge difference for me" (评论6)
中立/保留意见的观点: 1. D2虽好,但尚未成为行业标杆: - "D2 has a lot of merits but there’s little that sells it over PlantUML or Mermaid" (评论2) - "diagrams-as-code is still waiting for a killer program" (评论2)
- 编程语言集成存在挑战:
- "Looking at the syntax, I wonder how close one could get to it in a 'normal' programming language" (评论8)
- "a DSL for diagrams seems to be warranted" (评论8)
批评/改进建议的观点: 1. 企业版价格过高: - "Enterprise is way too expensive though... 3000usd / year for a single TALA license is... Well, not justifiable" (评论9)
- 缺乏"声明后调整"的工作流程:
- "The biggest problem with most of the declarative tools... is that they tend to not really offer 'declare, then tweak' workflows" (评论5)
开发者动态: - D2作者正在考虑扩展动画功能: - "Lately I've been noodling on the idea of expanding the animation capabilities" (评论7)
其他信息: - D2最近新增了ASCII渲染功能(评论4) - 有用户长期使用D2并积极推广(评论9)