Turn markdown into HTML using markdown-it
Learn how to use markdown-it, markdown-it-attrs and browserify

Markdown is great. It's easy to learn, has a reasonably straight forward sytax and is supported by many platfroms. But sometimes you need to more functionality than markdown traditionally allows. Like support for inserting id and class attributes for example.

By reading this article you will learn how to render markdown into HTML with attribute support. And we'll tie it all together with browserify in case you'll be running your code in the browser and not in node.

Use browserify to make npm packages browser friendly

Npm is super. There are litterly millions of packages to install. But what if the you don't want to, or can't, run your code using Node.js? How do you instead run that npm packaged code in the browser? Browserify to the resque.

The idea of browserify is as simple as one two three

  1. Install the npm packages you later want to run in a browser environment
  2. Create a JavaScript file that "requires" the desired packages
  3. Run browserify to generate a bundle

1 Installing packages using npm

First we need to install three packages: browserify markdown-it and markdown-it-attrs:

npm install markdown-it --save

npm install markdown-it-attrs --save

npm install -g browserify

2 Create a JavaScript file

Create a JavaScript called bundlesource.js file that looks something like so:

MarkdownIt = require('markdown-it');
markdownItAttrs = require('markdown-it-attrs');
md = new MarkdownIt();

Notice that we first create the MakdownIt object, and then implement support for id and class attributes with md.use(markdownItAttrs)

3 Use Browserify to generate a JavaScript bundle

Generate a bundle of both markdown-it and markdown-it-attrs by using browserify:

browserify bundlesource.js > bundle.js

You can now link the bundle.js from within the head HTML tag like this:

<script type="text/javascript" src="bundle.js"></script>

Running the code

The function to call to get markdown-it to render our markdown into HTML is simply called render. Since we've already enabled support for attributes we can just feed a string of markdown and watch the magic unfold:

var myMarkdownString = "### Render markdown with attributes {#titleStyling}"


This will in turn render the following HTML output:

<p id="titleStyling">
<h3>Render markdown with attributes</h3>

Robert Svensson

Tags: #JavaScript #browserify #markdown-it #markdown-it-attrs

2017-11-27 15:10:00

This is the personal website and article collection of me — Robert Svensson. I currently work for Contentful writing about APIs, coding and the future of content management

You can also find out what I'm up to by following me on GitHub, Twitter and LinkedIn. Feel free to send me an e-mail at [email protected]