Trey Kane Logo

Trey Kane

Implementing Highlight.js

February 18, 2024

Back to home

Implementing Highlight.js is by no means complicated, but finding all of the information I needed in one place was more difficult than it should have been. I wanted to share my implementation with the hopes that it may help someone else somewhere down the line.

First off, Highlight.js is a library you can add to your site that helps assist you with code highlighting. Offering some JS to help apply the target classes and CSS for applying color themes.

I usually try to keep things as simple as possible and that applies to this implementation as well. My goal was for this to be as low lift as possible, while offering me options and the results that will work with my implementation.

I started off by installing the package via NPM

npm install highlight.js

I then imported the JS for the package onto the page that renders my sites post template. I added the CSS here as well.

import hljs from 'highlight.js';
import 'highlight.js/styles/atom-one-dark.css';

The only other challenging part is figuring out the best way to apply initialize the scripts for that I turned to useEffect()

// Initialize highlight.js
useEffect(() => {
}, []);

My implementation still needs to be optimized so that I’m not importing highlighting for every language Highlight.js offers, but to get my implementation done quickly and easily this, did the trick!

Highlight.js is a really easy way to add code highlighting to your blog posts. I suggest you check it out, it can be implemented in a variety of ways, making it very flexible no matter what framework you choose to use for your blog.