网页渲染markdown(markdown-it)

markdown-it基础使用

安装markdown-it

text
1 2
npm install markdown-it --save

2、初始化markdown-it

text
1 2
import MarkdownIt  from "markdown-it"

3、渲染markdown文件

text
1 2 3 4 5
const markdownStr = 'xxxx'; // 需要渲染的markdown字符串
const md = new MarkdownIt();
const result = md.render(markdownStr);
return <div className="App" dangerouslySetInnerHTML={{__html: result}}></div>

markdown-it样式

由于markdown-it只是将markdown文件转化为html文件,所以还需要为其添加所需要的样式

1、添加基础样式

由于最总的渲染内容其实还是html,所以可以利用css自定义自己的样式 利用一些好看的已有样式,例如https://theme.typoraio.cn/上就有很多好看的markdown样式,可以将其加入到自己的项目中

2、代码高亮

代码高亮可以使用highlight.js

text
1 2 3 4 5 6 7 8 9 10 11 12 13 14
import hljs from "highlight.js";
  const md = new MarkdownIt({
   highlight: function (str, lang) {
     if (lang && hljs.getLanguage(lang)) {
      try {
        return hljs.highlight(lang, str).value;
      } catch (__) {}
     }

     return '';
   }
  });
  const result = md.render(str);

添加代码高亮的样式

在node_modules/highlight.js/styles目录下存在很多的高亮样式,挑选适合自己的样式,将其加入到自己的样式文件中

原文地址:https://blog.csdn.net/qq_36154659/article/details/125269768?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522168906542916800213021592%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=168906542916800213021592&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_ecpm_v1~rank_v31_ecpm-15-125269768-null-null.142^v88^control_2,239^v2^insert_chatgpt&utm_term=markdown