Markdown-it: Elegant Markdown Parser for Developers
Markdown-it is a powerful, pluggable Markdown parser that provides an extensive set of features and APIs, making it a preferred choice for developers. This article introduces Markdown-it and dives into its numerous useful APIs with practical code snippets to help you make the most out of it.
Getting Started with Markdown-it
To start using Markdown-it, you need to install it via npm:
npm install markdown-it --save
Basic Usage
Here’s a basic example of how you can use Markdown-it to convert Markdown to HTML:
const MarkdownIt = require('markdown-it');
const md = new MarkdownIt();
const result = md.render('# Markdown-it rulezz!');
console.log(result);
Advanced APIs
Use Plugins
Markdown-it allows you to extend its functionality using plugins:
const md = require('markdown-it')()
.use(require('markdown-it-emoji'));
console.log(md.render('I :heart: Markdown-it!'));
Custom Ruler
If you need custom rules, you can define and apply them:
const md = new MarkdownIt();
md.core.ruler.push('foo', function(state) {
console.log('Hello from custom rule!');
});
Token Modification
You can manipulate tokens directly:
md.core.ruler.before('linkify', 'replace-class', function replace(state) {
state.tokens.filter(token => token.type === 'link_open').forEach(token => {
var index = token.attrIndex('class');
if (index < 0) {
token.attrPush(['class', 'new-class']);
} else {
token.attrs[index][1] = 'new-class';
}
});
});
Inline Ruler
Custom inline rules can be defined as well:
md.inline.ruler.before('emphasis', 'example', function customRule(state, silent) {
if (state.src.charCodeAt(state.pos) !== 0x40 /* @ */) return false;
if (silent) return false;
const match = state.src.slice(state.pos).match(/^@example/);
if (!match) return false;
state.pos += match[0].length;
state.push({ type: 'text', content: 'example content' });
return true;
});
Markdown-it Application Example
Below is an example of an application using several Markdown-it features:
const express = require('express');
const MarkdownIt = require('markdown-it');
const emoji = require('markdown-it-emoji');
const app = express();
const md = new MarkdownIt().use(emoji);
app.use(express.json());
app.post('/convert', (req, res) => {
const result = md.render(req.body.markdown);
res.send(result);
});
app.listen(3000, () => console.log('Server is running on port 3000'));
This application sets up an Express server that receives Markdown input through a POST request and converts it to HTML using Markdown-it and the emoji plugin.
Markdown-it is a flexible and powerful tool for developers who need a robust Markdown parser. With its extensive APIs and plugin system, it can be tailored to fit a wide variety of use cases.
Happy coding with Markdown-it!
Hash: 29e7bb99c2c940abf7ce8492b405896c312a71a6987a807d5f6b68cc5b57acd3