starwait/docs/f01-mrkdown/marked/Marked使用方法.md
2025-04-29 02:39:55 +08:00

77 lines
4.6 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

## 导入
```js
// 只作用于当前空间
import { Marked } from 'marked';
const marked = new Marked();
// 全局
import { marked } from 'marked';
```
## 核心方法
| 方法 | 作用 | 示例 |
|:--------------------------|:----------------|:-----------------------------------------|
| marked.parse(md) | 同步解析 Markdown | await marked.parse('**bold**') |
| marked.parse(md, callback)| 异步解析(处理异步高亮等场景) | marked.parse(md, (err, html) => { ... }) |
| marked.use(options) | 全局配置 | marked.use({ breaks: true }) |
## 配置
```js
marked.use({
async: true,
pedantic: false,
gfm: true,
});
```
| 参数 | 类型 | 作用 | 默认值 |
|:-----------|:---------|:---------------------------------------------|:----------------|
| breaks | boolean | 将换行符 \n 渲染为 <br>(类似 GitHub | false |
| gfm | boolean | 启用 GitHub Flavored Markdown 扩展(表格、删除线等) | true |
| headerIds | boolean | 自动为标题添加 id 属性(如 `<h1 id="hello-world"></h1>` | true |
| highlight | function | 代码高亮处理函数,需返回高亮后的 HTML | null |
| renderer | object | 自定义渲染器对象(覆盖默认渲染逻辑) | new Renderer() |
| sanitize | boolean | 过滤危险 HTML 标签(防止 XSS 攻击) | false |
| sanitizer | function | 自定义 HTML 过滤函数 | - |
| silent | boolean | 静默模式:忽略解析错误(如未闭合的代码块) | false |
## 扩展 Markdown 语法
## 使用worker多线程
## 开启 sanitize: true 或使用 DOMPurify 二次过滤
## 性能优化
? 建议缓存常用操作
## renderer方法
| 方法名及参数 | 对应 Markdown 元素 | 默认返回值示例 |
|:-----------------------------------|:---------------------|:------------------------------------------|
| code(code, language, isEscaped) | 代码块(三个反引号包裹) | `<pre><code class="lang">...</code></pre>` |
| blockquote(quote) | 引用块 > | `<blockquote>...</blockquote>` |
| html(html) | 原生 HTML 片段 | 直接返回原始 HTML |
| heading(text, level, raw, slugger) | 标题 # | `<h1>...</h1>` |
| hr() | 分割线 --- | `<hr>` |
| list(body, ordered, start) | 列表(有序/无序) | `<ul>...</ul> 或 <ol>...</ol>` |
| listitem(text, task, checked) | 列表项 - item | `<li>...</li>` |
| checkbox(checked) | 任务列表复选框 - [x] | `<input type="checkbox" checked="">` |
| paragraph(text) | 段落 | `<p>...</p>` |
| table(header, body) | 表格 | `<table>...</table>` |
| tablerow(content) | 表格行 | `<tr>...</tr>` |
| tablecell(content, flags) | 表格单元格flags 含对齐信息) | `<td>...</td> 或 <th>...</th>` |
| strong(text) | 加粗 **text** | `<strong>...</strong>` |
| em(text) | 斜体 *text* | `<em>...</em>` |
| codespan(code) | 行内代码 `code` | `<code>...</code>` |
| br() | 换行(两个空格结尾或 br 配置) | `<br>` |
| del(text) | 删除线 ~~text~~ | `<del>...</del>` |
| link(href, title, text) | 链接 [text](url) | `<a href="...">...</a>` |
| image(href, title, text) | 图片 ![alt](url) | `<img src="..." alt="...">` |
| text(text) | 普通文本 | 直接返回文本(会转义 HTML |