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
- Create a Nuxt project and install highlight.js and Vue Highlight.js. To use highlight.js v10, use the next version of Vue Highlight.js.
npx create-nuxt-app nuxt-demo
cd nuxt-demo
npm i highlight.js vue-highlight.js@next
- Create Highlight.js plugin in
plugins/highlight.js
. Import and register the languages, as well the style you want to use. I do not seehtml
in the folder so I usexml
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
}
});
- Register the plugin in
nuxt.config.js
.
export default {
plugins: ["@/plugins/highlight"]
};
- 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
- Highlight code with
highlight-code
component. - Specify the language (opens new window) in the
lang
attribute. - It does not apply a style (opens new window) by default so you need to import one for this to work.