Utility

Code Blocks

Displays pre-formatted source code, with optional support for Highlight.js syntax highlighting.

typescript
import { CodeBlock } from '@skeletonlabs/skeleton';
Source Page Source Highlight.js

Demo

html
<div>This is meta</div>
css
.skeleton { color: #bada55; }
typescript
const skeleton: string = 'awesome';

Install Highlight.js

Highlight.js is a required dependency to enable syntax highlighting.

terminal
npm install highlight.js

Configure Your Project

To reduce your bundle size, we'll only import and register select languages for (ex: HTML, CSS, JS, TS). Please refer to the Highlight.js usage guide for more instruction.

typescript
import hljs from 'highlight.js/lib/core';

// Import each language module you require
import xml from 'highlight.js/lib/languages/xml'; // for HTML
import css from 'highlight.js/lib/languages/css';
import json from 'highlight.js/lib/languages/json';
import javascript from 'highlight.js/lib/languages/javascript';
import typescript from 'highlight.js/lib/languages/typescript';
import shell from 'highlight.js/lib/languages/shell';

// Register each imported language module
hljs.registerLanguage('xml', xml); // for HTML
hljs.registerLanguage('css', css);
hljs.registerLanguage('json', json);
hljs.registerLanguage('javascript', javascript);
hljs.registerLanguage('typescript', typescript);
hljs.registerLanguage('shell', shell);

Import any Highlight.js CSS theme of your choice.

typescript
import 'highlight.js/styles/github-dark.css';

Finally, import the CodeBlock's writable store and pass a referenced to Highlight.js.

typescript
import { storeHighlightJs } from '@skeletonlabs/skeleton';

storeHighlightJs.set(hljs);

Line Numbers

Adding the lineNumbers property will add line numbers to the displayed code. Supports up to 1000 lines of code.

html
	<p>
		The quick brown fox jumped over the lazy dog.
	</p>

Language

Syntax highlighting will appear when a valid language alias is provided to the Code Block's language property. For common web languages we recommend the shorthand values: html, css, js, ts, and shell.

Accessibility

Uses pre-wrap by default to support keyboard-only navigation. Please be mindful of color contrast ratios when customizing the design of your Code Block components.