Svelte Highlight

svelte-highlight provides Svelte components for code syntax highlighting using highlight.js.

Install using Yarn:

yarn add -D svelte-highlight

Install using NPM:

npm i -D svelte-highlight

SvelteKit set-up

To use this library with SvelteKit, add the following to the kit field in your svelte.config.js:

vite: {
  optimizeDeps: {
    include: ["highlight.js/lib/core"],
  },
}

Refer to the SvelteKit example for a sample set-up.

Basic usage

The default Highlight component requires two props:

  • code: text to highlight
  • language: language used to highlight the text

Languages can be found in "svelte-highlight/src/languages".

See the Languages page for a list of supported languages.

<script>
  import Highlight from "svelte-highlight";
  import typescript from "svelte-highlight/src/languages/typescript";
  import atomOneDark from "svelte-highlight/src/styles/atom-one-dark";

  const code = "const add = (a: number, b: number) => a + b;";
</script>

<svelte:head>
  {@html atomOneDark}
</svelte:head>

<Highlight language={typescript} {code} />

Styles can be imported from "svelte-highlight/src/styles".

There are two ways to add styles:

  • Injected styles: JavaScript styles injected using the svelte:head API
  • CSS StyleSheet: CSS file that may require an appropriate file loader

Refer to the Styles page for a list of supported styles.

Svelte syntax highlighting

Use the HighlightSvelte component for Svelte syntax highlighting.

<script>
  import { HighlightSvelte } from "svelte-highlight";
  import atomOneDark from "svelte-highlight/src/styles/atom-one-dark";
  
  const code = `<button on:click={() => { console.log(0); }}>Click me</button>`;
</script>

<svelte:head>
  {@html atomOneDark}
</svelte:head>

<HighlightSvelte {code} />

Auto-highlighting

The HighlightAuto component invokes the highlightAuto API from highlight.js.

<script>
  import { HighlightAuto } from "svelte-highlight";
  import atomOneDark from "svelte-highlight/src/styles/atom-one-dark";
  
  const code = ".body { padding: 0; margin: 0; }";
</script>

<svelte:head>
  {@html atomOneDark}
</svelte:head>

<HighlightAuto {code} />

TypeScript support

Svelte version 3.31 or greater is required to use this library with TypeScript.

TypeScript definitions are located in the types folder in the GitHub repository.

Examples

See the examples folder for sample set-ups including SvelteKit, Rollup, Webpack, Snowpack, and more.

License

MIT


Site last updated 7/8/2021, 8:20:39 AM