Convert Markdown string to HTML

brief introduction

The following plug-ins are used to realize the functions in turn: markdown string to HTML, automatic directory generation (toc), code highlighting, etc.

  • Markdown it: converts a markdown string into an HTML string;
  • HTML React parser: convert the above HTML string into React and use it to display the final typesetting in the web project of Node.js;
  • Markdown it anchor: add an anchor point to HTML and generate a document directory (TOC) with the plug-in;
  • Markdown it TOC done right: help markdown automatically generate a directory (TOC), which depends on the above plug-in markdown it anchor;
  • uslug: the TOC generated above sometimes fails to jump. The reason is that the anchor id generated by markdown it anchor does not match the herf generated by markdown it TOC done right. uslug can solve this problem;
  • The split line < HR / > cannot be displayed: the final HTML page cannot display the split line because there is no height. Set the height HR {height: 1px;} with css to display it.
  • highlight.js: after the code in markdown is parsed into HTML, it has no color, keyword highlight and other styles like normal text. This plug-in can solve the problem of code style.
markdown-it

Function: convert markdown string to HTML string

# install
npm i markdown-it

# use
// 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!');
html-react-parser

Function: convert HTML string into React element.

1. Installation
# npm installation
npm install html-react-parser --save

# yarn installation
yarn add html-react-parser

# CDN installation
<!-- HTMLReactParser depends on React -->
<script src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script src="https://unpkg.com/html-react-parser@latest/dist/html-react-parser.min.js"></script>
<script>
  window.HTMLReactParser(/* string */);
</script>
2. Use
# Convert HTML string to HTML
const parse = require('html-react-parser');
parse('<p>Hello, World!</p>'); // React.createElement('p', {}, 'Hello, World!')

# Converts an HTML string to HTML and replaces its attributes
parse('<p><br id="remove"></p>', {
  replace: ({ attribs }) => attribs && attribs.id === 'remove' && <></>
});

# Convert the HTML string to HTML and replace the tag < main / > with < div / >
import parse, { attributesToProps } from 'html-react-parser';

const html = `<main class="prettify" style="background: #fff; text-align: center;" />`;
const options = {
  replace: domNode => {
    if (domNode.attribs && domNode.name === 'main') {
      const props = attributesToProps(domNode.attribs);
      return <div {...props} />;
    }
  }
};
parse(html, options);
// Results after replacement:
<div class="prettify" style="background:#fff;text-align:center"></div>

3. Precautions
# Make sure there is a parent container, otherwise an error will occur
<ul>
  {parse(`
    <li>Item 1</li>
    <li>Item 2</li>
  `)}
</ul>
markdown-it-anchor

Function: used as a plug-in of markdown it to help the HTML parsed by markdown it, add anchor (< H / > tag, add id attribute), and then markdown-it-toc-done-right Plug in, you can automatically generate a directory (TOC) for markdown.

1. Installation
# install
npm i markdown-it-anchor

# use
const md = require('markdown-it')()
  .use(require('markdown-it-anchor'), opts)
2. Use attention
# Use the uslug plug-in to solve the unreadable character "% XX" in the anchor id.
$ npm i -S uslug

const uslug = require('uslug')
const uslugify = s => uslug(s)

const md = require('markdown-it')()
const anchor = require('markdown-it-anchor', {
    slugify: uslugify
})
uslug

Function: generate a sluify (unique string, remove or convert unreadable and unsupported characters) for string

1. Installation
npm install uslug
2. Use
# Call method
uslug(string, options)

# Parameter description
string Is the string to be passed in; options There are three values that can be set:
1,allowedChars:  You can specify that the string remains as it is without conversion. The default value is:'-_~'.
2,lower: Boolean value, cast to lowercase? Default to true
3,spaces: Boolean, allow spaces? Default to false.

# Use case
uslug('Быстрее и лучше!') // 'быстрее-и-лучше'
uslug('chinese/Chinese') // 'Chinese Chinese'

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. It can be used with other plug-ins
# Generate slugfy with markdown it anchor plug-in
# Generate slugfy with markdown it TOC done right plug-in
markdown-it-toc-done-right

Function: in the process of converting markdown string to HTML, generate directory (TOC), which depends on the plug-in: markdown it anchor

1. Installation
$ npm i -S markdown-it-toc-done-right markdown-it-anchor
2. Use
# node.js use case
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!");

# Another use scheme
// 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. Precautions
# In the process of use, the uslug plug-in is introduced, which can make the anchor id generated by markdown it anchor completely consistent with the href generated by markdown it TOC done right, so as not to cause the anchor jump failure due to different names.
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 } );
highlight.js

Function: let the code in markdown display different font styles (color, keyword highlighting, etc.)

1. Installation
# Environmental requirements
Node.js >= 12.x
npm >= 6.x

# npm installation
npm install highlight.js

# yarn installation
yarn add highlight.js
2. Load and call
#1. Automatically identify the code language and highlight it with the corresponding language format
const hljs = require('./highlight.js');
const highlightedCode = hljs.highlightAuto('<span>Hello World!</span>').value

#2. Use to determine the code language format
html = hljs.highlight('<h1>Hello World!</h1>', {language: 'xml'}).value

#3. Customize the format for each code element module
// first, find all the div.code blocks
document.querySelectorAll('div.code').forEach(el => {
  // then highlight each
  hljs.highlightElement(el);
});
3. Choose a style to present the final effect
# Find your favorite css in the path "/ node_modules/highlight.js/styles", copy the file to the project and load it when you use it
import "../components/shades-of-purple.css"

# For the actual display style, see the style link given by the official below
markdown-it-multimd-table
1. Installation
npm i markdown-it-multimd-table
2. Use case 1
// 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. Use case 2
$ mkdir markdown-it-multimd-table
$ cd markdown-it-multimd-table
$ npm install markdown-it-multimd-table --prefix .
$ vim test.js

    var 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
Reference documents

Tags: html markdown

Posted on Tue, 30 Nov 2021 21:59:39 -0500 by BigJohn