Posts Learn Categories Tags About
/
How to add HightlightJs for Nuxt JS application cover

How to add HightlightJs for Nuxt JS application

Learn how to add syntax highlighting for NuxtJs application and make it more appealing

5 months ago

6 mins read

15 views

In this post, you'll learn how to integrate Higlight.js for Nuxt Js application. For this example, I will assume that Highlight.js will only be used on a certain page and not globally available for all pages, this way it will only be available on the pages which only need it hence saving the load on every page. The steps are quite straightforward but don't miss any of them.

Add Highlight.js
yarn add highlight.js
npm install highlight.js

Add highlight.js to the project, do run the command based on the package manager that you chose for the project.

Initialize Highlight.Js
Let's assume that you want to highlight blog content that's accessible within "/blogs/_slug" page, in the _slug.vue page you will have to initialize the highlight.js code.

<template>
  <div v-html="blog.content"/>
</template>

<script>
import hljs from 'highlight.js'

export default {
  data () {
    return {
      blog: {}
    }
  },

  async fetch() {
    // get the blog content e
  }

  mounted () {
    /* init highlight.js */
    setTimeout(function () {
      document.querySelectorAll('pre')
        .forEach((block) => {
          hljs.highlightBlock(block)
        })
    }, 1000)
  }
}
</script>

<style src="highlight.js/styles/tomorrow.css"></style>

The code above consisting of 3 parts, the template part is to load the blog content which will be displayed on the page by outputting real HTML.

Secondly, the script section will contain the initialization part where the highlight.js is imported and invoked inside the mounted. The way how this works is that it'll find all "pre" tags on the page and loop through them while highlighting each of the blocks. Do note that we wrap this code inside a setTimeout function and this is necessary to ensure that the content is fully loaded before being highlighted.

Lastly, the style tag will import the theme that'll be used and in this example, it will be tomorrow.css. By default, it comes with 97 different styles as of this writing and I recommend that you look through their theme collection to get the right one for you.