web #javascript

Highlighting Code Snippets for the Web - highlight.js

Jan 6 '19 · 2 min read · 619

Code snippets for the web using highlight.js

Why?

G

ood looking code is important for readability, which of course makes it more likely that someone will understand your code and even want to read it in the first place! Even basic editors like nano have code highlighting. If you're not highlighting your code, it's almost pointless having it on the web in the first place - especially on a tutorial or blog.

"Beauty is more important in computing than anywhere else in technology because software is so complicated. Beauty is the ultimate defence against complexity."
- David Gelernter

One thing I have learnt from starting this blog is that making code snippets for the web look as good as they do in your favorite text editor yourself is tedious, time-consuming and a solved problem already - hello highlight.js!

highlight.js

Being over 10 years old, highlight.js has been solving this problem for a while already. It is a great library that - at the time of writing - supports 185 languages and 89 different themes/styles. Other features include:

Getting Started

Getting started is easy. First, go to the download page where you can download a custom bundle that includes only your selected languages - this is recommended if you want to keep your site lean. Then unzip the bundle, and copy the 'highlight.pack.js' file into your project's public '/js/libs/' directory - or wherever you want it. In the 'styles' directory of the unzipped bundle, choose a style you want to use - swap them out until you find one you like - and copy it to your preferred project public css directory - '/css/libs/atom-one-dark.css'.

Once you have these two files in place, there are only three steps left - add the files to your HTML head, call 'hljs.initHighlightingOnLoad()', and insert your code into the markup. The JavaScript file will search for code inside of <pre><code>some code</pre></code> tags. The library will try to automatically detect the language, but you can add a class to the <code class="html"> tag to specify the language manually. See the documentation for more.

Include the files and call the script initializer

<link rel="stylesheet" href="/css/libs/atom-one-dark.css">
<script src="/js/libs/highlight.pack.js"></script>
<script>hljs.initHighlightingOnLoad();</script>

Wrap your code in <pre><code> tags

<pre><code>console.log(someCode);</code></pre>

A final note to be aware of: watch out for spacing! Start your code immediately after and on the same line as the <code> tag. All spaces and new lines will be rendered, so make sure you keep it consistent for indenting your code. If there is a bunch of extra space you didn't want - it is probably because there are extra spaces in your markup (writing from experience).