跳到主要内容

Mardown增加PlantUML的渲染

· 阅读需 1 分钟
Lichlaughing

PlantUML 画图

依靠docusaurus.config.jsmarkdown的配置中的preprocessor方法。

以及Javascript API Client Code——PlantUML官网

需要做三件事:

To use PlantUML image generation, a text diagram description have to be :

  1. Encoded in UTF-8
  2. Compressed using Deflate algorithm
  3. Reencoded in ASCII using a transformation close to base64

最主要的就是利用算法Deflate得到转换后的字符串,这个已经有开源项目给整理好了 plantuml-encoder 拿过来直接使用即可。

首先编写md


```plantuml
@startuml
Bob -> Alice : hello
@enduml
```

配置文件增加

var plantumlEncoder = require('plantuml-encoder')

markdown: {
mermaid: true,
preprocessor: ({ filePath, fileContent }) => {
const plantumlNodeRegex = /```plantuml[\s\S]*?```/gm;
const plantumlContentRegex = /(?<=```plantuml)[\s\S]*?(?=```)/g;
if (filePath.search('docs') != -1) {
let m;
const str = fileContent;
while ((m = plantumlNodeRegex.exec(str)) !== null) {
if (m.index === plantumlNodeRegex.lastIndex) {
plantumlNodeRegex.lastIndex++;
}
m.forEach((match, groupIndex) => {
let n;
while ((n = plantumlContentRegex.exec(match)) !== null) {
if (n.index === plantumlContentRegex.lastIndex) {
plantumlContentRegex.lastIndex++;
}
n.forEach((match2, groupIndex2) => {
fileContent = fileContent.replaceAll(
match,
'![](https://www.plantuml.com/plantuml/svg/' +
plantumlEncoder.encode(match2) +
')'
);
});
}
});
}
}
return fileContent;
}
}

如果你想自己搞的话,参考rawdeflate.js 来着 https://github.com/johan/js-deflate 。但是需要注意这中文编码的问题,可能中文乱码。