将Markdown字符串转成HTML

简介 使用以下插件,依次实现:markdown字符串转HTML、自动生成目录(toc)、代码高亮等功能。

  • markdown-it:将markdown字符串转换成HTML字符串;
  • html-react-parser:将上面HTML字符串转换成React,用在Node.js的web项目中展示最终排版;
  • markdown-it-anchor:给HTML增加锚点,配合插件即可生成文档的目录(TOC);
  • markdown-it-toc-done-right:帮markdown自动生成目录(TOC),依赖上面插件markdown-it-anchor
  • uslug:上面生成的目录(TOC),有时候跳转会失败,原因就是markdown-it-anchor生成锚点id 与 markdown-it-toc-done-right 生成的herf 不匹配导致,uslug可解决此问题;
  • 分割线无法显示:最终HTML页面无法显示分割线,原因是没有高度导致,用css设置高度hr{ height: 1px; }即可显示。
  • highlight.js:markdown中代码解析成HTML后,跟正常文字一样是没有颜色、关键字高亮等样式的,此插件即可解决代码样式问题。
markdown-it 功能:把markdown字符串转换为HTML字符串.
# 安装 npm i markdown-it# 使用 // node.js, "classic" way: var MarkdownIt = require('markdown-it'), md = new MarkdownIt(); var result = md.render('# markdown-it rulezz!'); // node.js, the same, but with sugar: var md = require('markdown-it')(); var result = md.render('# markdown-it rulezz!');

  • markdown-it 源码
  • markdown-it 插件下载
  • Live Demo:查看markdown字符串变HTML的效果
  • markdown-it 中文文档
html-react-parser 功能:将HTML字符串转成React元素。
1、安装
# npm安装 npm install html-react-parser --save# yarn安装 yarn add html-react-parser# CDN安装

2、使用
# 将HTML字符串转换为HTML const parse = require('html-react-parser'); parse('Hello, World!
'); // React.createElement('p', {}, 'Hello, World!')# 将HTML字符串转换为HTML并替换其中属性 parse('

', { replace: ({ attribs }) => attribs && attribs.id === 'remove' && <> }); # 将HTML字符串转换为HTML并替换其中标签
为 import parse, { attributesToProps } from 'html-react-parser'; const html = `
`; const options = { replace: domNode => { if (domNode.attribs && domNode.name === 'main') { const props = attributesToProps(domNode.attribs); return ; } } }; parse(html, options); // 替换后结果:

3、注意事项
# 确保有父容器,否则会出错
    {parse(`
  • Item 1
  • Item 2
  • `)}

  • html-react-parser插件下载
  • html-react-parser源码
markdown-it-anchor 功能:作为markdown-it的插件使用,帮助markdown-it解析后的HTML,加上锚点(标签增加id属性),再配合上markdown-it-toc-done-right插件,就可以为markdown自动生成目录(TOC)。
1、安装
# 安装 npm i markdown-it-anchor# 使用 const md = require('markdown-it')() .use(require('markdown-it-anchor'), opts)

2、使用注意
# 用uslug插件,解决锚点id中,「%XX」这种不可读的字符。 $ npm i -S uslugconst uslug = require('uslug') const uslugify = s => uslug(s)const md = require('markdown-it')() const anchor = require('markdown-it-anchor', { slugify: uslugify })

  • markdown-it-anchor 插件下载
  • markdown-it-anchor 源码
uslug 功能:为string生成一个slugify(唯一字符串,去掉或转换不可读、不支持的字符).
1、安装
npm install uslug

2、使用
# 调用方法 uslug(string, options)# 参数说明 string是待传入的字符串;options有三个值可以设置: 1、allowedChars:可以指定字符串保持原样,不转换,缺省值:'-_~'. 2、lower: 布尔值,是否强制转换为小写?缺省为true 3、spaces: 布尔值,是否允许空格?缺省为false.# 使用案例 uslug('Быстрее и лучше!') // 'быстрее-и-лучше' uslug('汉语/漢語') // '汉语漢語'uslug('Y U NO', { lower: false })) // 'Y-U-NO' uslug('Y U NO', { spaces: true })) // 'y u no' uslug('Y-U|NO', { allowedChars: '|' })) // 'yu|no'

3、可以配合其他插件使用
# 配合 markdown-it-anchor 插件生成slugify # 配合 markdown-it-toc-done-right 插件生成slugify

  • uslug 插件下载
  • uslug源码
markdown-it-toc-done-right 功能:为markdown字符串转HTML过程中,生成目录(TOC),依赖插件:markdown-it-anchor
1、安装
$ npm i -S markdown-it-toc-done-right markdown-it-anchor

2、使用
# node.js 使用案例 var md = require("markdown-it")({ html: false, xhtmlOut: true, typographer: true }).use( require("markdown-it-anchor"), { permalink: true, permalinkBefore: true, permalinkSymbol: '§' } ) .use( require("markdown-it-toc-done-right") ); var result = md.render("# markdown-it rulezz!\n\n${toc}\n## with markdown-it-toc-done-right rulezz even more!"); # 另外一种使用方案 // browser without AMD, added to "window" on script load // Note, there is no dash in "markdownit". var md = window.markdownit({ html: false, xhtmlOut: true, typographer: true }).use( window.markdownItAnchor, { permalink: true, permalinkBefore: true, permalinkSymbol: '§' } ) .use( window.markdownItTocDoneRight ); var result = md.render("# markdown-it rulezz!\n\n${toc}\n## with markdown-it-toc-done-right rulezz even more!");

3、注意事项
# 使用过程中,引入uslug插件,这样可以使得markdown-it-anchor生成锚id,跟markdown-it-toc-done-right生成的href能够完全一致,不至于因为名称不同导致锚点跳转失败。 var md = require("markdown-it")({ html: false, xhtmlOut: true, typographer: true }).use( require("markdown-it-anchor"), { permalink: true, permalinkBefore: true, permalinkSymbol: '§', { slugify: uslugify} } ) .use( require("markdown-it-toc-done-right"), { slugify: uslugify } );

  • markdown-it-toc-done-right 插件下载
  • markdown-it-toc-done-right 源码
highlight.js 【将Markdown字符串转成HTML】功能:让markdown中代码,显示不同的字体样式(彩色、关键字高亮等).
1、安装
# 环境要求 Node.js >= 12.x npm >= 6.x# npm安装 npm install highlight.js# yarn安装 yarn add highlight.js

2、加载并调用
#1.自动识别代码语言,并使用对应语言格式高亮 const hljs = require('./highlight.js'); const highlightedCode = hljs.highlightAuto('Hello World!').value#2.使用确定代码语言格式高亮 html = hljs.highlight('Hello World!', {language: 'xml'}).value#3.对各个代码元素模块,自定义格式 // first, find all the div.code blocks document.querySelectorAll('div.code').forEach(el => { // then highlight each hljs.highlightElement(el); });

3、选择样式,呈现最后效果
# 在此路径「/node_modules/highlight.js/styles」,找到喜欢的css,复制文件到项目中,使用时加载 import "../components/shades-of-purple.css"# 实际展示样式可以看下面官方给出的样式链接

  • 官网
  • 官方 - 使用手册
  • 官方 - 样式效果展示
markdown-it-multimd-table 1、安装
npm i markdown-it-multimd-table

2、使用案例一
// defaults var md = require('markdown-it')() .use(require('markdown-it-multimd-table')); // full options list (equivalent to defaults) var md = require('markdown-it')() .use(require('markdown-it-multimd-table'), { multiline:false, rowspan:false, headerless: false, }); md.render(/*...*/)

3、使用案例二
$ mkdir markdown-it-multimd-table $ cd markdown-it-multimd-table $ npm install markdown-it-multimd-table --prefix . $ vim test.jsvar md = require('markdown-it')() .use(require('markdown-it-multimd-table')); const exampleTable = "||Grouping|| \n" + "First Header| Second Header | Third Header | \n" + " ------------ | :-----------: | -----------: | \n" + "Content|*Long Cell*|| \n" + "Content|**Cell**|Cell | \n" + "\n" + "New section|More|Data | \n" + "And more| With an escaped '\\|'|| \n" + "[Prototype table]\n"; console.log(md.render(exampleTable)); $ node test.js > test.html $ firefox test.html

  • markdown-it-multimd-table插件下载
  • markdown-it-multimd-table源码
参考文档
  • 将Markdown字符串转成HTML

    推荐阅读