Posts Learn Snippets Categories Tags About
/
Using highlight.js on laravel project cover

Using highlight.js on laravel project

Beautify your code example with highlight js and make it easily readable

1 month ago

8 mins read

1000 views

In this post, you'll learn how to syntax highlight your code example and make it easily readable. The steps are very straight forward so follow along and let's start implementing it.

Install dependencies
The dependency that we'll need is Highlight Js and you can use npm to install it.
npm install highlight.js
yarn add highlight.js // if you are using yarn

Implementation
Since we'll be using Laravel mix, create a new file called "hljs" inside the "resources/js" folder then pass it through laravel mix in order to process the file with webpack. 
mix
    .js('resources/js/hljs.js', 'public/js')
    .sass('resources/css/app.scss', 'public/css');

Javascript Initialization
The content of the hljs should be as follow. Do note that we are wrapping the whole code in a setTimeout to ensure that the highlight code only run after 1 second the page is loaded, this is to ensure that everything is on the page and ready.
import hljs from 'highlight.js';

setTimeout(function () {
    document
        .querySelectorAll('pre')
        .forEach((block) => hljs.highlightElement(block));
}, 1000);

Code Theme Styling
Since Highlight Js also come with many different styles you can use, do pick the right one for your website. For more details of the available themes do visit this page Highlight Js Demo.

Now inside the "app.scss" do import the styling so that your code looks beautiful. In this case, we'll import the "idea" theme and it will be used for the highlighting.
/* highlight js */
@import "~highlight.js/styles/idea.css";

The last part for this to work is to import the javascript to your layout file. You will have to use the mix method for this and it's as follows.
<!DOCTYPE html>
<html>
<head>
  <!-- head content -->
</head>
<body>
    <!-- body content -->

    <script src="{{ mix('js/hljs.js') }}" defer></script>
</body>
</html>

Now any of the code example that you have on your website will automatically be processed with Highlight Js. If you find this tutorial to be helpful do share it with others and cheers, happy coding!