Given the subject of this blog, I’ll be using code blocks often, and right now they look like blocks of poo. I’m going to use the highlight.js library to make them awesome.
It’s tempting to plop the highlight.js css and js files directly in header.php, but I’ll do this the right way.
First I need to install highlight.js
I’m using laravel-mix to transpile my javascript and scss, so I’ll install it using npm. This will add both the javascript and scss dependencies.
Install highlight.js
npm i highlight.js
Next I initialize the library
After requiring the library, I’ll apply it by calling the initHighlightingOnLoad method. By default, this will modify the contents of all <pre> tags. You can specify the language of the code block by adding a class to the pre tag manually, but highlight.js does a good job of inferring the language from the text, and that’s good enough for me. Based on the syntax of the language used in the code block, highlight.js colors the key words by wrapping them in tags and applying css classes to those tags.
const hljs = require("highlight.js")
const result = hljs.initHighlightingOnLoad()
Adding the styles is the next logical step, otherwise this is all for nothing
/* import theme */
@import "highlight.js/scss/vs2015.scss";
The last step is to verify it works. I’m going to verify this outside of the WordPress editor.
Never trust a WYSIWYG when you are depending on specific markup. Sure, I’ll need to deal with that soon, but I’ll save that party for another day. For now, I’m simply going to hard code the markup structure highlight.js expects and see if it works.
<pre>
<code>
echo 'this used to look like poo';
echo 'it looks awesome now, thanks to highlight.js';
</code>
</pre>
And voilĂ ! Awesome code blocks.
But they can be better
Because I’m using tailwindcss, making the code blocks look even better is a breeze. I want to polish this up by adding some padding, a nice border and a bit of shadow.
pre {
@apply p-3 shadow-md bg-gray-100 border border-gray-300 my-6;
}
Let’s see where we are now
<pre>
<code>
echo 'this used to look like poo';
echo 'then it looked awesome, thanks to highlight.js';
echo 'and now it looks super awesome, thanks to tailwindcss';
</code>
</pre>
I’m happy with this look. Time to move on to the next thing.