How to Apply Syntax Highlighting with highlight.js

Introduction
 

highlight.js is an open source JavaScript library for highlighting code in web pages. It supports a wide range of programming languages and is easy to use.

Want to apply syntax highlighting to your code snippets on your pages? This tutorial on highlight.js is for you.
I use this library for my articles, and I can' recommend it enough! 🎨

In this guide we will see :
 

  • The overall use of the library.
  • The optimization of the resources involved.
  • How to integrate the plugin hljs-line-numbers which allows to display the line numbers.

 


Installation

 

CDN
 

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/default.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js"></script>


Npm
 

npm install highlight.js

 


Usage


First of all we need to import the library if you use npm. Highlight.js is also available in ES6 Module.

ES6 Module
 

import hljs from 'highlight.js';


CommonJS
 

const hljs = require( 'highlight.js' );

 

The .highlightAll() method will perform the necessary modifications on the DOM elements in order to apply syntax highlighting.

 

hljs.highlightAll();

 

To apply syntax highlighting to a code snippet, simply surround it with the pre and code tags, and add the hljs and language-<Name of language> classes. Here is an example:
 

<pre><code class="hljs language-javascript">
function add(a, b) {
	return a + b;
}
const sum = add(1, 2);
</code></pre>


And here we are with a nice snippet of color code!
 

function add(a, b) {
	return a + b;
}
const sum = add(1, 2);


If you are using the CKEditor WYSIWYG editor and want to integrate a compatible highlight.js code snippet generator (plugin) to your toolbar, I will show you how in this article.

 


Change theme


CDN
 

If you want to change the theme (syntax highlighting style), modify the CSS file loaded from the CDN with the one you want. You can find the list of all available themes on CDNJS.
For this blog, I use the codepen-embed theme!
 

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/codepen-embed.min.css" />


SCSS
 

/* Using a CDN */
@import "https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/styles/codepen-embed.min.css";

/* Import from node_modules */
@import "~highlight.js/scss/codepen-embed";


 

Performance optimization
 

Let's see some optimizations that we can apply to what we have seen before.


Defer loading


The library is quite heavy when it is imported entirely (we will see soon how to lighten it), it takes time to be loaded and is blocking when loaded synchronously, let's optimize this loading by applying the defer attribute as follow:
 

<head>
	<!-- ... -->
	<script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.7.0/highlight.min.js" defer></script>
</head>

<body>
    <!-- ... -->
	<script>
		window.addEventListener("load", () => {
		    hljs.highlightAll();
		})
	</script>
</body>


With defer, the library is loaded in parallel without stopping the rendering of the rest of the page. You must then make sure that you only use the hljs instance once the page has been rendered by listening to the load event.


Import only what is necessary
 

Loading the whole highlight.js library represents a significant performance cost. We have seen how to import the library globally, now let's see how to import only what we need, that is language by language.

 

CommonJS

 

// Getting the core
const hljs = require( 'highlight.js/lib/core' );

// Registration of desired languages
hljs.registerLanguage( 'scss', require( 'highlight.js/lib/languages/scss' ) );
hljs.registerLanguage( 'javascript', require( 'highlight.js/lib/languages/javascript' ) );

 

ES6 Module

 

// Getting the core
import hljs from 'highlight.js/lib/core';

// Getting the desired languages
import scss from 'highlight.js/lib/languages/scss';
import javascript from 'highlight.js/lib/languages/javascript';

// Registration of desired languages
hljs.registerLanguage('scss', scss);
hljs.registerLanguage('javascript', javascript);

 


Adding line numbers
 

Unfortunately for us, the column with line numbers is not included in the library by default, the author of the library explains why here.
But good news: This user volunteered to create a plugin that does the job and it is very easy to install and integrate. A command line, a small addition of Javascript and a few CSS lines will do the trick! 🥳
Follow the guide.


Installation


CDN

 

<script src="https://cdnjs.cloudflare.com/ajax/libs/highlightjs-line-numbers.js/2.8.0/highlightjs-line-numbers.min.js"></script>

 

<script src="https://cdn.jsdelivr.net/npm/highlightjs-line-numbers.js@2.8.0/dist/highlightjs-line-numbers.min.js"></script>

 

Npm

 

npm install highlightjs-line-numbers.js

 

Usage


Just import highlightjs-line-numbers.js and call the .initLineNumbersOnLoad() method after our highlight.js configuration:

 

require('highlight.js');
require('highlightjs-line-numbers.js');

hljs.highlightAll();
hljs.initLineNumbersOnLoad();


Finally, we add some CSS to get a nice result:

 

.hljs-ln-numbers {
	-webkit-touch-callout: none;
	-webkit-user-select: none;
	-khtml-user-select: none;
	-moz-user-select: none;
	-ms-user-select: none;
	user-select: none;
	text-align: center;
	color: #ccc;
	border-right: 1px solid rgba(204, 204, 204, 0.514);
	vertical-align: top;
	word-break: normal; /* Avoid a line break on large line numbers */
}

.hljs-ln td:nth-child(1) {
	padding-right: 10px;
}

.hljs-ln td:nth-child(2) {
	padding-left: 10px;
}

Discover related posts

0 comment