How to Use Highlight.js in a Nuxt Project demo repo

Highlight.js (opens new window) is a syntax highlighting tool for the Web.

Vue Highlight.js (opens new window) is a syntax highlighter component for Vue.

Before, I used Prism (opens new window) for syntax highlighting with vue-prism-component (opens new window) as the wrapper. But I find the plugin, e.g. Autolinker (opens new window) does not always work, so I switched to this.

# 👣 Steps

  1. Create a Nuxt project and install highlight.js and Vue Highlight.js. Vue Highlight.js does not support highlight.js v10 at the time of this writing so just install the latest v9 version.
npx create-nuxt-app nuxt-demo
cd nuxt-demo
npm i highlight.js@9.18.3 vue-highlight.js
  1. Create Highlight.js plugin in plugins/highlight.js. Import and register the languages, as well the style you want to use. I do not see html in the folder so I use xml instead.
import Vue from "vue";
import VueHighlightJS from "vue-highlight.js";

import javascript from "highlight.js/lib/languages/javascript";
import scss from "highlight.js/lib/languages/scss";
import xml from "highlight.js/lib/languages/xml";

import "highlight.js/styles/dracula.css";

Vue.use(VueHighlightJS, {
  languages: {
    javascript,
    scss,
    xml
  }
});
  1. Register the plugin in nuxt.config.js.
export default {
  plugins: ["@/plugins/highlight"]
};
  1. Use Highlight.js, e.g. in pages/highlight.vue.
<template>
  <div>
    <h1>Highlight Demo</h1>

    <h2>HTML</h2>
    <highlight-code lang="xml">{{ html }}</highlight-code>

    <h2>JavaScript</h2>
    <!-- prettier-ignore -->
    <highlight-code lang="js">
      const me = {
        name: "Yasmin ZY", country: "Indonesia"
      }
    </highlight-code>

    <h2>SCSS</h2>
    <!-- prettier-ignore -->
    <highlight-code lang="scss">
      .grid {
        display: grid;
        @media (min-width: 576px) {
          grid-template-columns: 1fr 1fr;
        }
      }
  </highlight-code>
  </div>
</template>

<script>
export default {
  data() {
    return {
      html: `<article>
  <h1 class="title">How to Use Highlight.js in a Vue/Nuxt Project</h1>
  <p>Go to https://yasminzy.com/tutorial/highlight/</p>
</article>`
    };
  }
};
</script>

<style scoped>
pre:not(:last-of-type) {
  margin-bottom: 2rem;
}
</style>

# 📖 Explanation

Last updated: 11/1/2020, 3:28:11 PM