网页渲染markdown(markdown-it)

白色玫瑰 程序猿

时间: 2023-07-11 阅读: 1 字数:2515

{}
使用markdown-it在网页上渲染markdown文件

网页渲染markdown(markdown-it)

markdown-it基础使用

安装markdown-it

npm install markdown-it --save

2、初始化markdown-it

import MarkdownIt  from "markdown-it"

3、渲染markdown文件

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

import hljs from "highlight.js";
  const md = new MarkdownIt({
   highlight: function (str, lang) {
     if (lang &amp;&amp; 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

本文章网址:https://www.sjxi.cn/detil/076615e6e9264754a5a29ac88e869c9d

最新评论

当前未登陆哦
登陆后才可评论哦

湘ICP备2021009447号