Parse markdown and highlight code in a Nuxt project

published at Jul 31, 2020
#Vuejs#Nuxt

I recently rebuild my website with Nuxt. For writing posts, I decided to use a headless CMS, named Storyblok. Most of the content in my post are in Markdown. And when I needed to parse Markdown and highlight code, I faced multiple alternatives. Here is the choice I made.

I used a Nuxt module, markdownit, combined with markdown-it-highlightjs.

First, install the dependencies:

yarn add markdown-it-highlightjs

Next, in your nuxt.config.js file, add the markdownit module, configure it and import css:

export default {
  css: [   
    // use the theme you want. There are many options. Here below is the theme I choose, a nice one made by Sarah Drasner
    // https://github.com/sdras/night-owl-vscode-theme
    {
      src: '~/node_modules/highlight.js/styles/night-owl.css',
      lang: 'css'
    },
   // ... your own CSS
  ],
  modules: [
    '@nuxtjs/markdownit',
    // other modules
  ],
  markdownit: {
    injected: true,
    use: ['markdown-it-highlightjs']
  },
  // ... your nuxt config
}

There are different options to render markdown. Please read the documentation of markdownit to render it. Quite simple. Like so:

<template>   
    <div v-html="$md.render(md_content)" />
</template>