Install dependencies
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";
<!DOCTYPE html> <html> <head> <!-- head content --> </head> <body> <!-- body content --> <script src="{{ mix('js/hljs.js') }}" defer></script> </body> </html>