@ 创建- markdown/ 预览
框架- 不可知 HTML 渲染为 @ create- markdown 有语法加亮( Shiki) 和图支持( Mermaid) .
安装
# Using pnpm
pnpm add @create-markdown/preview
# Using npm
npm install @create-markdown/preview
# Optional: Install plugins
pnpm add shiki
快速启动
基本 HTML 渲染
import { markdownToHTML } from '@create-markdown/preview';
import DOMPurify from 'dompurify';
const html = await markdownToHTML(`
# Hello World
This is **bold** and *italic* text.
`);
const preview = document.getElementById('preview');
if (preview) {
preview.innerHTML = DOMPurify.sanitize(html, { USE_PROFILES: { html: true } });
}
在渲染之前先对不可信的内容进行无害化处理. 直接 DOM 任务只有在完全信任下标源时才合适 .
带有语法加亮 (Shiki)
import { renderAsync, shikiPlugin } from '@create-markdown/preview';
import { parse } from '@create-markdown/core';
const blocks = parse(`
\`\`\`typescript
const greeting = "Hello, World!";
console.log(greeting);
\`\`\`
`);
const html = await renderAsync(blocks, {
plugins: [shikiPlugin({ theme: 'github-dark' })],
});
有美人鱼图
import { renderAsync } from '@create-markdown/preview';
import { mermaidPlugin } from '@create-markdown/preview-mermaid';
import { parse } from '@create-markdown/core';
const blocks = parse(`
\`\`\`mermaid
flowchart LR
A[Start] --> B[Process]
B --> C[End]
\`\`\`
`);
const html = await renderAsync(blocks, {
plugins: [
mermaidPlugin({
theme: 'default',
config: { securityLevel: 'strict' },
}),
],
});
仅在需要时安装人鱼支持 :
pnpm add @create-markdown/preview-mermaid mermaid
在图文可以来自用户时使用美人鱼更严格的安全模式. 只为完全信任的内容选择松散的美人鱼设置 .
网络组件
<script type="module">
import { registerPreviewElement } from '@create-markdown/preview';
registerPreviewElement();
</script>
<markdown-preview theme="github">
# Hello World
This is rendered as HTML automatically!
</markdown-preview>
带有插件 :
import { registerPreviewElement, shikiPlugin } from '@create-markdown/preview';
import { mermaidPlugin } from '@create-markdown/preview-mermaid';
registerPreviewElement({
plugins: [
shikiPlugin(),
mermaidPlugin(),
],
});
网络组件默认会让可信内容生效,因此在将用户提供的标记传递给元素之前,先对用户提供的标记进行消毒.
API 密码
blocksToHTML(blocks, options?)
将块同步转换为 HTML 字符串 .
markdownToHTML(markdown, options?)
将下标字符串转换为 HTML .
renderAsync(blocks, options?)
在渲染前初始化插件的Async版本.
插件
shikiPlugin(options?)- 与Shiki一起突出语法mermaidPlugin(options?)- 美人鱼图透视@create-markdown/preview-mermaid
主题
CSS主题见:
@create-markdown/preview/themes/github.css@create-markdown/preview/themes/github-dark.css@create-markdown/preview/themes/minimal.css
选项
interface PreviewOptions {
classPrefix?: string; // CSS class prefix (default: 'cm-')
theme?: string; // Theme name
linkTarget?: '_blank' | '_self';
sanitize?: boolean | ((html: string) => string);
plugins?: PreviewPlugin[]; // Plugins for enhanced rendering
}
许可证
麻省理工学院