import { marked } from 'marked' import { markedHighlight } from 'marked-highlight' import katex from 'katex' import hljs from 'highlight.js' function renderMath(text, displayMode) { try { return katex.renderToString(text, { displayMode, throwOnError: false, strict: false, }) } catch { return text } } // marked extension for inline math $...$ const mathExtension = { name: 'math', level: 'inline', start(src) { const idx = src.search(/(?${renderMath(token.text, true)}` }, } // 配置 marked 支持代码高亮 marked.use(markedHighlight({ langPrefix: 'hljs language-', highlight(code, lang) { const language = hljs.getLanguage(lang) ? lang : 'plaintext' return hljs.highlight(code, { language }).value } })) marked.use({ gfm: true, breaks: true, extensions: [blockMathExtension, mathExtension] }) export function renderMarkdown(text) { return marked.parse(text) }