Skip to content

使用方法 ​

🌐 Usage

Mermaid 是一个 JavaScript 工具,使用基于 Markdown 的语法来渲染可自定义的图表、图示和可视化内容。

🌐 Mermaid is a JavaScript tool that makes use of a Markdown based syntax to render customizable diagrams, charts and visualizations.

可以通过修改图表的描述来重新渲染或修改图表。

🌐 Diagrams can be re-rendered/modified by modifying their descriptions.

内容分发网络 ​

🌐 CDN

https://www.jsdelivr.com/package/npm/mermaid

请注意,你可以通过右上角的下拉框切换版本。

🌐 Please note that you can switch versions through the dropdown box at the top right.

使用 Mermaid ​

🌐 Using mermaid

对于大多数用户来说,使用 Live Editor 就足够了,但你也可以选择将 mermaid 作为依赖部署或使用 Mermaid API。

🌐 For the majority of users, Using the Live Editor would be sufficient, however you may also opt to deploy mermaid as a dependency or using the Mermaid API.

我们整理了一些关于如何使用 Mermaid 实时编辑器的视频教程。

🌐 We have compiled some Video Tutorials on how to use the Mermaid Live Editor.

在网页上安装和托管 Mermaid ​

🌐 Installing and Hosting Mermaid on a Webpage

使用 npm 包:

要求:

🌐 Requirements:

  • Node.js >= 22.12.0

支持的浏览器和运行时 ​

🌐 Supported browsers and runtimes

Mermaid v12.0.0+ 发布的包是针对 ES2024 的,并且旨在支持 Safari 17.4 或更高版本。

🌐 Mermaid v12.0.0+'s published bundles target ES2024 and are aimed to support Safari 17.4 or later.

我们也会对 Chromium 121 和 Firefox 123 做代码检查,但不像 Safari 17.4 那样,我们不会承诺支持这些过时的版本。

🌐 We run linting for Chromium 121 and Firefox 123 support as well, but unlike Safari 17.4, we don't commit to supporting these outdated versions.

旧一点的浏览器可能也能用,或者你可能需要对 mermaid 做 polyfill/转译来支持它们。

🌐 Older browsers may work too, or you may need to polyfill/transpile mermaid to support them.

bash
# NPM
npm install mermaid
# Yarn
yarn add mermaid
# PNPM
pnpm add mermaid

在网页上托管 Mermaid:

注意:本主题在初学者用户指南中有更深入的探讨

在网页上集成 mermaid 最简单的方法需要两个元素:

🌐 The easiest way to integrate mermaid on a web page requires two elements:

  • 一个图表定义,位于标记为 class=mermaid 的 <pre> 标签内。

示例:

🌐 Example:

html
<pre class="mermaid">
    graph LR
    A --- B
    B-->C[fa:fa-ban forbidden]
    B-->D(fa:fa-spinner);
</pre>
  • Mermaid(mermaid)JS 脚本。使用 script 标签作为 ESM 导入添加。

示例:

🌐 Example:

html
<script type="module">
  import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@12/dist/mermaid.esm.min.mjs';
</script>

按照这些说明,mermaid 会在页面加载时启动,并且(当页面加载完成后)会在带有 class="mermaid" 的 pre 标签中查找图表定义,并根据给定的定义以 SVG 形式返回图表。

字体 ​

🌐 Fonts

Mermaid 目前根据图表类型和所选主题使用几种不同的默认 fontFamily 设置。

🌐 Mermaid currently uses a few different default fontFamily settings, based on the diagram type and the given theme.

当前首选的字体有:

🌐 The current preferred fonts are:

为了保持一致的外观,我们建议你尽可能提供这些作为网页字体,例如:

🌐 For a consistent look, we recommend you supply these as web fonts, when possible, e.g. like:

html
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fontsource/open-sans@5/400.css" />
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fontsource/open-sans@5/400-italic.css" />
<link
  rel="stylesheet"
  href="https://cdn.jsdelivr.net/npm/@fontsource-variable/recursive@5/index.css"
/>

简单完整示例: ​

🌐 Simple full example:

html
<!doctype html>
<head>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fontsource/open-sans@5/400.css" />
  <link
    rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/@fontsource/open-sans@5/400-italic.css"
  />
  <link
    rel="stylesheet"
    href="https://cdn.jsdelivr.net/npm/@fontsource-variable/recursive@5/index.css"
  />
</head>
<html lang="en">
  <body>
    <pre class="mermaid">
  graph LR
      A --- B
      B-->C[fa:fa-ban forbidden]
      B-->D(fa:fa-spinner);
    </pre>
    <script type="module">
      import mermaid from 'https://cdn.jsdelivr.net/npm/mermaid@12/dist/mermaid.esm.min.mjs';
    </script>
  </body>
</html>

注意事项: ​

🌐 Notes:

对于没有 id 属性的 mermaid 标签,也会添加一个 id 属性。

🌐 An id attribute is also added to mermaid tags without one.

Mermaid 可以在同一页面加载多个图表。

🌐 Mermaid can load multiple diagrams, in the same page.

试一试,把这段代码保存为 HTML 文件,然后用任意浏览器打开。 (除了 Internet Explorer,请不要使用 Internet Explorer。)

小 Mermaid ​

🌐 Tiny Mermaid

我们提供了一个较小版本的 Mermaid,大小大约是完整库的一半。这个小版本不包含思维导图、架构图、KaTeX 渲染、懒加载,也没有 ELK 布局引擎。

🌐 We offer a smaller version of Mermaid that's approximately half the size of the full library. This tiny version doesn't include Mindmap Diagrams, Architecture Diagrams, KaTeX rendering, lazy loading, or the ELK layout engine.

如果你需要一个没有这些功能的更轻量版本,可以使用 Mermaid Tiny。

🌐 If you need a more lightweight version without these features, you can use Mermaid Tiny.

ELK 和小型构建 ​

🌐 ELK and the tiny build

这个精简版本从来没有包含 ELK,现在也没有——因为它是一个很大的依赖,而保持小巧正是这个版本的重点。这里要求 ELK 布局的图会退回到 Dagre 并正常渲染;没有什么会坏掉,它们只是由 Dagre 来布局。

🌐 The tiny build has never included ELK, and still doesn't — it is a large dependency and staying small is the point of that build. Diagrams that ask for an ELK layout here fall back to Dagre and still render; nothing breaks, they are simply laid out by Dagre.

v12.0.0 改变的是主包,不是这个包:以前 ELK 是可选的 @mermaid-js/layout-elk 安装,现在和 mermaid 打包在一起并且默认使用。所以 如果你想要没有 ELK 的 Mermaid,使用精简版才是办法 —— 现在不安装布局包已经不够了。

🌐 What changed in v12.0.0 is the main package, not this one: ELK used to be an opt-in @mermaid-js/layout-elk install, and is now bundled with mermaid and used by default. So if you want a Mermaid without ELK, the tiny build is the way to get one — it is no longer simply a matter of not installing the layout package.

如果你想要小型版本 和 ELK,同时注册 @mermaid-js/layout-elk。正是为了这种情况,这个包才会持续发布:

🌐 If you want the tiny build and ELK, register @mermaid-js/layout-elk alongside it. That package continues to be published for exactly this case:

html
<script src="https://cdn.jsdelivr.net/npm/@mermaid-js/tiny/dist/mermaid.tiny.js"></script>
<script type="module">
  import elkLayouts from 'https://cdn.jsdelivr.net/npm/@mermaid-js/layout-elk/dist/mermaid-layout-elk.esm.min.mjs';

  // The tiny build is an IIFE that assigns `globalThis.mermaid`, so it is loaded
  // with a plain `<script>` tag and used as a global — there is no default
  // export to import.
  mermaid.registerLayoutLoaders(elkLayouts);
  mermaid.initialize({ startOnLoad: true, layout: 'elk' });
</script>

注册这个包也会让指定的 ELK 算法可用 —— elk.stress、elk.force、elk.mrtree、elk.sporeOverlap、elk.box 和 elk.rectpacking。在普通的 mermaid 构建中,你根本不需要这个包:注册它无害但多余,因为这些布局已经内置了。

🌐 Registering the package also makes the named ELK algorithms available — elk.stress, elk.force, elk.mrtree, elk.sporeOverlap, elk.box and elk.rectpacking. On a normal mermaid build you do not need this package at all: registering it is harmless but redundant, since the same layouts are already built in.

在节点中启用点击事件和标签 ​

🌐 Enabling Click Event and Tags in Nodes

securityLevel 配置必须首先清除。securityLevel 设置解析图表的信任级别,并限制点击功能。它在 8.2 版本中作为安全改进引入,旨在防止恶意使用。

🌐 A securityLevel configuration has to first be cleared. securityLevel sets the level of trust for the parsed diagrams and limits click functionality. This was introduced in version 8.2 as a security improvement, aimed at preventing malicious use.

区分可信赖和不可信赖的用户群体是网站所有者的责任,我们鼓励谨慎使用判断。

securityLevel ​

参数描述类型必填值
securityLevel已解析图表的信任等级字符串可选'sandbox', 'strict', 'loose', 'antiscript'

值:

🌐 Values:

  • 严格: (默认) 文本中的 HTML 标签已被编码,点击功能已被禁用。
  • antiscript:文本中允许包含 HTML 标签(仅移除 script 元素),并启用点击功能。
  • 宽松:文本中允许使用 HTML 标签,并启用点击功能。
  • 沙盒:在此安全级别下,所有渲染都在沙盒化的 iframe 中进行。这会阻止任何 JavaScript 在上下文中运行。这可能会影响图表的互动功能,如脚本、时序图中的弹出窗口、链接到其他标签或目标等。

信息

这会改变 mermaid 的默认行为,因此在升级到 8.2 后,除非修改了 securityLevel,流程图中的标签将被编码为标签,并且点击功能会被禁用。 sandbox 安全级别仍处于测试版本。

如果你负责图表源的安全性,你可以将 securityLevel 设置为你选择的值。这允许点击和标签被使用。

要更改 securityLevel,你必须调用 mermaid.initialize:

javascript
mermaid.initialize({
  securityLevel: 'loose',
});

标签超出范围 ​

🌐 Labels out of bounds

如果你使用通过 CSS 动态加载的字体,例如自定义字体,mermaid 应该等待整个页面加载完成(DOM + 资源,特别是字体文件)。

🌐 If you use dynamically loaded fonts that are loaded through CSS, such as fonts, mermaid should wait for the whole page to load (dom + assets, particularly the fonts file).

javascript
$(document).ready(function () {
  mermaid.initialize();
});

如果不这样做,很可能会导致 mermaid 渲染的图表标签超出边界。mermaid 的默认集成使用 window.load 事件来开始渲染。

🌐 Not doing so will most likely result in mermaid rendering graphs that have labels out of bounds. The default integration in mermaid uses the window.load event to start rendering.

如果你的页面正文中有其他字体,可能会使用这些字体而不是 Mermaid 字体。在样式中指定字体是解决此问题的一种方法。

🌐 If your page has other fonts in its body those might be used instead of the mermaid font. Specifying the font in your styling is a workaround for this.

css
pre.mermaid {
  font-family: 'trebuchet ms', verdana, arial;
}

使用 mermaid.run ​

🌐 Using mermaid.run

mermaid.run 在 v10 中添加,是处理更复杂集成的首选方法。默认情况下,当文档准备就绪时,将调用 mermaid.run,渲染所有带有 class="mermaid" 的元素。

🌐 mermaid.run was added in v10 and is the preferred way of handling more complex integration. By default, mermaid.run will be called when the document is ready, rendering all elements with class="mermaid".

你可以通过调用 await mermaid.run(<config>) 来自定义该行为。

mermaid.initialize({startOnLoad: false}) 将阻止 mermaid.run 在加载后自动调用。

使用 querySelector ".someOtherClass" 渲染所有元素

🌐 Render all elements with querySelector ".someOtherClass"

js
mermaid.initialize({ startOnLoad: false });
await mermaid.run({
  querySelector: '.someOtherClass',
});

渲染作为数组传递的所有元素

🌐 Render all elements passed as an array

js
mermaid.initialize({ startOnLoad: false });
await mermaid.run({
  nodes: [document.getElementById('someId'), document.getElementById('anotherId')],
});
await mermaid.run({
  nodes: document.querySelectorAll('.yetAnotherClass'),
});

渲染所有 .mermaid 元素,同时抑制任何错误

🌐 Render all .mermaid elements while suppressing any error

js
mermaid.initialize({ startOnLoad: false });
await mermaid.run({
  suppressErrors: true,
});

调用 mermaid.init - 已弃用 ​

🌐 Calling mermaid.init - Deprecated

警告

mermaid.init 在 v10 中已被弃用,将在未来版本中移除。请改用 mermaid.run。

默认情况下,mermaid.init 会在文档就绪时被调用,查找所有具有 class="mermaid" 的元素。如果你在 Mermaid 加载后添加内容,或者需要对该行为进行更精细的控制,可以自行调用 init,方法如下:

🌐 By default, mermaid.init will be called when the document is ready, finding all elements with class="mermaid". If you are adding content after mermaid is loaded, or otherwise need finer-grained control of this behavior, you can call init yourself with:

  • 一个配置对象
  • 一些节点,作为
    • 一个节点
    • 类似数组的节点
    • 或 W3C 选择器,用于查找你的节点

示例:

🌐 Example:

javascript
mermaid.init({ noteMargin: 10 }, '.someOtherClass');

或者没有配置对象,直接使用 jQuery 选择器:

🌐 Or with no config object, and a jQuery selection:

javascript
mermaid.init(undefined, $('#someId .yetAnotherClass'));

在 webpack 中的使用 ​

🌐 Usage with webpack

Mermaid 完全支持 webpack。这里有一个可运行的演示。

🌐 mermaid fully supports webpack. Here is a working demo.

API 使用 ​

🌐 API usage

该 API 的主要思想是能够使用图表定义的字符串调用渲染函数。渲染函数将渲染图表,并使用生成的 SVG 代码调用回调函数。通过这种方法,由网站创建者负责从网站获取图表定义(可能来自文本区域)、渲染图表并将图表放置在网站的某个位置。

🌐 The main idea of the API is to be able to call a render function with the graph definition as a string. The render function will render the graph and call a callback with the resulting SVG code. With this approach it is up to the site creator to fetch the graph definition from the site (perhaps from a textarea), render it and place the graph somewhere in the site.

下面的示例展示了如何使用它。该示例只是将生成的 SVG 日志记录到 JavaScript 控制台中。

🌐 The example below shows an example of how this could be used. The example just logs the resulting SVG to the JavaScript console.

html
<script type="module">
  import mermaid from './mermaid.esm.mjs';
  mermaid.initialize({ startOnLoad: false });

  // Example of using the render function
  const drawDiagram = async function () {
    element = document.querySelector('#graphDiv');
    const graphDefinition = 'graph TB\na-->b';
    const { svg } = await mermaid.render('graphDiv', graphDefinition);
    element.innerHTML = svg;
  };

  await drawDiagram();
</script>

要确定给定文本中存在的图表类型,可以使用 mermaid.detectType 函数,如下面的示例所示。

🌐 To determine the type of diagram present in a given text, you can utilize the mermaid.detectType function, as demonstrated in the example below.

html
<script type="module">
  import mermaid from './mermaid.esm.mjs';
  const graphDefinition = `sequenceDiagram
    Pumbaa->>Timon:I ate like a pig.
    Timon->>Pumbaa:Pumbaa, you ARE a pig.`;
  try {
    const type = mermaid.detectType(graphDefinition);
    console.log(type); // 'sequence'
  } catch (error) {
    // UnknownDiagramError
  }
</script>

绑定事件 ​

🌐 Binding events

有时生成的图表也具有定义好的交互功能,如工具提示和点击事件。在使用 API 时,必须在图表插入到 DOM 后再添加这些事件。

🌐 Sometimes the generated graph also has defined interactions like tooltip and click events. When using the API one must add those events after the graph has been inserted into the DOM.

下面的示例代码是使用 API 时 Mermaid 的部分功能示例。该示例展示了在使用渲染 API 时如何将事件绑定到 SVG。

🌐 The example code below is an extract of what mermaid does when using the API. The example shows how it is possible to bind events to an SVG when using the API for rendering.

javascript
// Example of using the bindFunctions
const drawDiagram = async function () {
  element = document.querySelector('#graphDiv');
  const graphDefinition = 'graph TB\na-->b';
  const { svg, bindFunctions } = await mermaid.render('graphDiv', graphDefinition);
  element.innerHTML = svg;
  // This can also be written as `bindFunctions?.(element);` using the `?` shorthand.
  if (bindFunctions) {
    bindFunctions(element);
  }
};
  1. 该图表是使用渲染调用生成的。
  2. 生成后,渲染函数会调用提供的回调函数,在此例中它被称为 insertSvg。
  3. 回调函数会被调用并传入两个参数:生成图表的 SVG 代码和一个函数。这个函数会在 SVG 插入到 DOM 后绑定事件。
  4. 将 SVG 代码插入 DOM 以进行展示。
  5. 调用绑定事件的绑定函数。

一个标记渲染器示例 ​

🌐 Example of a marked renderer

这是用于将文档从 Markdown 转换为带有 mermaid 图表的 HTML 的渲染器。

🌐 This is the renderer used for transforming the documentation from Markdown to html with mermaid diagrams in the html.

javascript
const renderer = new marked.Renderer();
renderer.code = function (code, language) {
  if (code.match(/^sequenceDiagram/) || code.match(/^graph/)) {
    return '<pre class="mermaid">' + code + '</pre>';
  } else {
    return '<pre><code>' + code + '</code></pre>';
  }
};

另一个 CoffeeScript 示例,它还在生成的标记中包含了 mermaid 脚本标签。

🌐 Another example in CoffeeScript that also includes the mermaid script tag in the generated markup.

coffee
marked = require 'marked'

module.exports = (options) ->
  hasMermaid = false
  renderer = new marked.Renderer()
  renderer.defaultCode = renderer.code
  renderer.code = (code, language) ->
    if language is 'mermaid'
      html = ''
      if not hasMermaid
        hasMermaid = true
        html += '<script src="'+options.mermaidPath+'"></script>'
      html + '<pre class="mermaid">'+code+'</pre>'
    else
      @defaultCode(code, language)

  renderer

高级用法 ​

🌐 Advanced usage

无需渲染的语法验证 ​

🌐 Syntax validation without rendering

mermaid.parse(text, parseOptions) 函数在不渲染图表的情况下验证图表定义。

🌐 The mermaid.parse(text, parseOptions) function validates graph definitions without rendering a graph.

函数 mermaid.parse(text, parseOptions) 接受一个文本字符串作为参数,如果定义遵循 mermaid 的语法,则返回 { diagramType: string }。

🌐 The function mermaid.parse(text, parseOptions), takes a text string as an argument and returns { diagramType: string } if the definition follows mermaid's syntax.

如果定义无效,当 parseOptions.suppressErrors 设置为 true 时,函数返回 false。否则,它会抛出一个错误。

🌐 If the definition is invalid, the function returns false if parseOptions.suppressErrors is set to true. Otherwise, it throws an error.

当 parse 函数抛出错误时,将调用 parseError 函数。如果 parseOptions.suppressErrors 设置为 true,则不会调用该函数。

🌐 The parseError function will be called when the parse function throws an error. It will not be called if parseOptions.suppressErrors is set to true.

可以重写此函数,以便以特定于应用的方式处理错误。

🌐 It is possible to override this function in order to handle the error in an application-specific way.

下面的元代码示例说明了这如何运作:

🌐 The code-example below in meta code illustrates how this could work:

javascript
mermaid.parseError = function (err, hash) {
  displayErrorInGui(err);
};

const textFieldUpdated = async function () {
  const textStr = getTextFromFormField('code');

  if (await mermaid.parse(textStr)) {
    reRender(textStr);
  }
};

bindEventHandler('change', 'code', textFieldUpdated);

配置 ​

🌐 Configuration

你可以将所需的配置传递给 mermaid.initialize 调用。这是配置 mermaid 的首选方式。配置对象的列表在 mermaidAPI 文档 中有说明。

🌐 You can pass the required configuration to the mermaid.initialize call. This is the preferred way of configuring mermaid. The list of configuration objects are described in the mermaidAPI documentation.

html
<script type="module">
  import mermaid from './mermaid.esm.mjs';
  let config = { startOnLoad: true, htmlLabels: true, flowchart: { useMaxWidth: false } };
  mermaid.initialize(config);
</script>

信息

这是配置 Mermaid 的首选方式。

以下方法已被弃用,仅为向后兼容而保留。 ​

🌐 The following methods are deprecated and are kept only for backwards compatibility.

使用 Mermaid 对象 ​

🌐 Using the mermaid object

可以通过 mermaid 对象设置一些配置。使用这种方法支持的两个参数是:

🌐 It is possible to set some configuration via the mermaid object. The two parameters that are supported using this approach are:

  • mermaid.startOnLoad
  • mermaid.htmlLabels
javascript
mermaid.startOnLoad = true;

警告

这种设置配置的方式已被弃用。更推荐的做法是使用 initialize 方法。此功能仅为向后兼容而保留。

Opens in mermaid.ai