·Publikoval Frank Hliva·3 min čítania

Syntax Highlighter for Your Website – highlight.js

Syntax Highlighter for Your Website – highlight.js

You have probably noticed that this website contains beautifully formatted code blocks. I was looking for a clever, fast, single-purpose solution that would not take up too much space, and I found this: https://highlightjs.org/. So let’s show how it actually works.

First, you need to install the npm package:

yarn add highlight.js

or (if you use npm):

npm i highlight.js --save

In your source HTML code, the block to be highlighted must be wrapped in pre and code tags. Don’t forget the "language-" class prefix – although the library can function without it, we need it for our specific automation purposes.

<pre>
	<code class="language-javascript">
		... any source code here
	</code>
</pre>

Let’s also look at how this is written in Markdown (if you are unfamiliar with Markdown, check here). As you probably know, in Markdown, we do not need to explicitly write the "language-" prefix because the markdown parser appends it to the generated HTML automatically:

```javascript
	... any source code here
```

Next, we need to import the required files (I am using TypeScript syntax; in pure JS, remove the "* as"):

/* TypeScript syntax (if you use pure JS, remove "* as") */
import * as highlightJS from 'highlight.js/lib/highlight';
import 'highlight.js/styles/vs2015.css'; // You can choose from many styles

import * as javascript from 'highlight.js/lib/languages/javascript';
highlightJS.registerLanguage('javascript', javascript);
highlightJS.initHighlightingOnLoad();

Notice those last three lines: if we want to highlight a language’s syntax, we must import it first and then explicitly register it. In this example, only JavaScript is registered. If we use C# in our code blocks, the highlighter will not highlight it.

When I first encountered this, I wondered if the author of the library was serious – why make it so complicated? But then it occurred to me that the pre and code elements already contain the name of the language inside their CSS class name. And our beautiful Markdown parser prepends the "language-" prefix to them, which is perfect because we can use it to determine which CSS class represents the language name.

And here is our solution:

So I wrote a small script. It checks which languages are used in the pre/code blocks on the page and dynamically registers the corresponding highlighters. Of course, the language name used in your pre/code block must match the filename of the highlight.js language file (e.g., javascript, not JS), and it must be prefixed with "language-" (unless you use a Markdown parser that appends it automatically). Here is my script (released under the Public Domain, so do whatever you want with it):

import * as highlightJS from 'highlight.js/lib/highlight';
import 'highlight.js/styles/vs2015.css';
import * as javascript from 'highlight.js/lib/languages/javascript';

const registerRelevantLanguages = (highlightJS) => {
    let registeredLanguages = new Set<string>();
    document.querySelectorAll('pre code').forEach(element => {
        const prefixedName = element.className.split(' ').find(c => c.startsWith('language-'));
        if (typeof prefixedName === "string") {
            const names = prefixedName.split('-');
            if (names.length === 2) {
                const languageName = names[1];
                if (!registeredLanguages.has(languageName)) {
                    const language = require(`highlight.js/lib/languages/${languageName}`);
                    highlightJS.registerLanguage(languageName, language);
                    registeredLanguages.add(languageName);
                }
            }
        }
    });
}
registerRelevantLanguages(highlightJS);
highlightJS.initHighlightingOnLoad();

Ta-da! That’s it. You don’t have to worry about anything else – everything is imported automatically. Of course, for better code organization, it’s best to place this function in its own module (that part is up to you).

Share:
Späť na blog

Súvisiace čítanie

Ďalšie články z blogu

Zobraziť všetky články