May 2, 2025
Create your own Markdown-It Plugin
Customize your markdown rendering with plugins.
By Ross Robinomd / markdown-it / plugin
Markdown-It is a popular markdown parser that converts markdown into HTML. It supports all the basic commonmark syntax out of the box.
It’s nice to be able to extend the parser if you need more customization. For example, the @shikijs/markdown-it plugin highlights code blocks with Shiki (in my opinion this is the best reason to use Markdown-It over another parser!). There are many other plugins made by the community, notably the mdit-plugins packages.
In this post we’ll go through how to use the parser and how to create your own plugins.
To get started with Markdown-It, you can install the package from npm.
The parser is a class with a render method that converts markdown into HTML.
To add a plugin, you can use the use method, you can use as many plugins as you like.
Here’s an example from the @mdit/plugin-img-lazyload plugin.
Here’s how you can create your own Markdown-It plugin. I’ll create a tableOverflow plugin that adds a <div style="overflow-x: auto"> element around each <table> element so they will not overflow off of the page horizontally.
@types/markdown-it provides some type helpers to ensure your plugin works with the use method.
Markdown-It creates an array of tokens that you can modify with a RenderRule in a plugin. The tokens get passed through each RenderRule as they are being parsed.
To add or modify a RenderRule within a plugin, you can set a property on the mdIt.renderer.rules object. It’s a best practice when implementing a plugin to extend the original render rule rather than overwrite it. We’ll create a proxy as the default if it’s not set already.
In this case, we’ll check to see if there’s already table_open and table_close rules that another plugin has set. If they aren’t defined, we’ll set the originals to the proxy.
Next, we’ll modify the rules on the Markdown-It instance. We’ll use the original rule within our own rule, adding the <div> element before and after the table, and passing all the args directly into the original.
Our tableOverflow plugin is now complete, we have updated the Markdown-It instance with our own rules via the plugin.
You can also modify a token within the plugin. For example, you can set an attribute on a token with the attrSet method. This is how the @mdit/plugin-img-lazyload plugin works.
Here’s another example of a YouTube embed plugin. Here we can replace the <img> element with an <iframe> if the image src starts with "yt:".
So now the following code will produce a YouTube embed rather than an image.
Those are the basics of creating your own custom Markdown-It plugin. You can use the Markdown-It website in debug mode to view a list of the tokens generated from any stream of markdown to understand which rules apply to which elements and more properties that can be set or modified.
Thanks for reading!…