雁过留声 发表于 2024-11-3 00:12:53

怎样在前端vue3中处理markdown并使用样式和代码高亮

怎样在前端vue3中处理markdown并使用样式和代码高亮

由于想要在前端实现实时渲染markdown,发现找不到对应的处理。搜了很久,终于找到了需要的方法,在这里分享一下
最终效果展示:
https://i-blog.csdnimg.cn/blog_migrate/14e6b0145e52c527b5cd69ff232e1b21.png#pic_center
在前端vue3中处理markdown

读取markdown为string文本,然后通过最后markdown-it包转成markdown文件。
markdown-it | markdown-it 中文文档 (docschina.org)
安装依赖:
npm install markdown-it --save
用法:script setup中
import MarkdownIt from 'markdown-it'

md = new MarkdownIt();
var result = md.render('# markdown-it rulezz!'); //传入文本
template中直接用v-html绑定:
<div v-html="result"></div>
最终在页面表现:
https://i-blog.csdnimg.cn/blog_migrate/20178a7513f00ba1c12499b1a25b4443.png#pic_center
此时会发现如果有代码的话,代码框没有样式,也没有高亮
导入一些其他的样式应该也是可以的,只需要看文件是怎么用引入的就行
给markdown添加样式

sindresorhus/github-markdown-css:复制 GitHub Markdown 样式的最小 CSS 数量
可以添加GitHub的markdown样式
npm install github-markdown-css
引入依赖:
import 'github-markdown-css';
在生成表现markdown的标签加上对应的class:
<div v-html="item.content" class="markdown-body" style="font-size: small"></div>
可以根据需求引入官方这个:
<style>
        .markdown-body {
                box-sizing: border-box;
                min-width: 200px;
                max-width: 980px;
                margin: 0 auto;
                padding: 45px;
        }

        @media (max-width: 767px) {
                .markdown-body {
                        padding: 15px;
                }
        }
</style>
然后发现有样式了,但是没有代码高亮
所以还需要加一点东西
wooorm/starry-night: Syntax highlighting, like GitHub
starry-night会生成基于代码高亮的html的hast 树大概css样式,以及自定义语法,具体可以看官方文档。
syntax-tree/hast-util-to-html:将 hast 序列化为 HTML 的实用步伐 (github.com)
hast-util-to-html将html的hast 树转成HTML的工具。
两者的结合可以生成高亮的代码html文本
安装依赖:
npm install @wooorm/starry-night
npm install hast-util-to-html
官方示例:
import fs from 'node:fs/promises'
import {common, createStarryNight} from '@wooorm/starry-night'
import {toHtml} from 'hast-util-to-html'
import markdownIt from 'markdown-it'

const file = await fs.readFile('example.md')
const starryNight = await createStarryNight(common)

const markdownItInstance = markdownIt({
highlight(value, lang) {
    const scope = starryNight.flagToScope(lang)

    return toHtml({
      type: 'element',
      tagName: 'pre',
      properties: {
      className: scope
          ? [
            'highlight',
            'highlight-' + scope.replace(/^source\./, '').replace(/\./g, '-')
            ]
          : undefined
      },
      children: scope
      ? /** @type {Array<ElementContent>} */ (
            starryNight.highlight(value, scope).children
          )
      : [{type: 'text', value}]
    })
}
})

const html = markdownItInstance.render(String(file))

console.log(html)
在代码中使用上就有一开始所先容的效果了。
怎么实时表现流输出的markdown文本数据

可以看一下我写的这篇文章,说得很详细,有我本人写的具体实现:
vue3前端使用ollama搭建本地模型处理流并实时生成markdown-CSDN博客

免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
页: [1]
查看完整版本: 怎样在前端vue3中处理markdown并使用样式和代码高亮