- 安裝 marked + highlight.js 依賴
cnpm i marked highlight.js --save
- 引入 marked + highlight.js
import marked from 'marked' import hljs from "highlight.js"; import 'highlight.js/styles/monokai-sublime.css'; //第三項中的css 高亮主題可以自己更換自己喜歡的
- marked 配置highlight.js
marked.setOptions({ renderer: new marked.Renderer(), gfm: true, pedantic: false, sanitize: false, tables: true, breaks: true, smartLists: true, smartypants: true, highlight: function (code) { return hljs.highlightAuto(code).value; } });
上邊的三步配置完後就可以通過
let html=marked(mdcontent)
的方式轉換md 内容為html 并進行渲染了,但是需要注意的是在react 中直接對需要渲染的地方使用
dom.innerText=html
的方式進行渲染會渲染出marked 轉化出的字元串,這不是我們想要的結果 ,需要強制将字元串轉化為html 代碼,另一篇文章有提到 React标簽字元串強制轉html的方法
以上操作完畢後就基本能夠達到想要的效果了,如果想讓代碼塊突出顯示的話 可以設定
pre code
标簽的 css,我的設定如下:
/* 代碼塊高亮 */
pre {position: relative;margin-bottom: 24px;border-radius: 3px;border: 1px solid #C3CCD0;background: #FFF;overflow: hidden;}
code {display: block;padding: 12px 24px;overflow-y: auto;font-weight: 300;font-family: Menlo, monospace;}
code.has-numbering {margin-left: 21px;}
.pre-numbering {position: absolute;top: 0;left: 0;width: 20px;padding: 12px 2px 12px 0;border-right: 1px solid #C3CCD0;border-radius: 3px 0 0 3px;background-color: #EEE;text-align: right;font-family: Menlo, monospace;font-size: 0.8em;color: #AAA;}