Add Syntax Highlighting to your NuxtJS Blog

Table of Contents

A cool programming blog won't be complete if you don't have a proper syntax highlighting feature for your code. It just makes easier for your audience to read your blog. This is how you can setup your syntax highlighting feature in your NuxtJS blog.

Install highlight.js

npm install --save highlight.js 

Create a Vue Plugin

Under the plugins folder, create a new file and name it highlight.plugin.ts. Paste the code below:

import Hljs from 'highlight.js/lib/highlight'
import 'highlight.js/styles/monokai-sublime.css'

Hljs.registerLanguage('php', require('highlight.js/lib/languages/php'))
Hljs.registerLanguage(
  'javascript',
  require('highlight.js/lib/languages/javascript')
)
Hljs.registerLanguage('css', require('highlight.js/lib/languages/css'))
Hljs.registerLanguage('bash', require('highlight.js/lib/languages/bash'))

const Highlight = {}
Highlight.install = (Vue, options) => {
  Vue.directive('highlight', (el) => {
    const blocks = el.querySelectorAll('pre code')
    blocks.forEach((block) => {
      Hljs.highlightBlock(block)
    })
  })
}

export default Highlight

Notes

Most tutorials will tell you to use import Hljs from 'highlight.js' when importing highlight.js. The problem with this is you will end up with a big bundle size because it will import all the available language.

We use import Hljs from 'highlight.js/lib/highlight' so we can only import languages that our blog supports.

To add a language, simply call

Hljs.registerLanguage('php', require('highlight.js/lib/languages/php'))

You can browse available languages in node_modules/highlight.js/lib/languages.

Next is select your preferred theme. I used monokai-sublime theme in this website. You can browse more theme in node_modules/highlight.js/styles.

Import the Plugin to your Next Site

Now we need to tell nuxtjs to use this plugin. Under plugins directory, create a plugin.js file and paste the code below:

import Vue from 'vue'
import Highlight from './highlight.plugin'

Vue.use(Highlight)

You can also use plugin.js as an entry point to your other plugins.

Now in your nuxt.config.js file, add the following options to the plugins options.

    /*
     ** Plugins to load before mounting the App
     */
    plugins: [
      ...
      '~/plugins/plugins.js'
    ],

This will now load the highlight plugin in your nuxt site.

Use the directive in your vue component

You can now use the directive in your vue components.

<template>
    <div class="post">
      <article class="post__content markdown-body" v-highlight>
        <code></code>
      </article>
    </div>
  </div>
</template>
...

Conclusion

Highlight.js supports tons of programming languages and comes with cool css themes. If you are having trouble, contact me and I can help you with your blog πŸ˜ƒ.