metonym / svelte-highlight

Syntax Highlighting for Svelte using highlight.js
https://svhe.onrender.com
MIT License
262 stars 14 forks source link

Add dynamic import example #219

Closed metonym closed 2 years ago

metonym commented 2 years ago

This is less of an issue for SvelteKit which will already code-split your app.

However, for other SPA set-ups, it would be nice to have a quick primer on dynamically importing a language grammar, which can be quite heavy.

mcndt commented 2 years ago

+1 on this. Currently trying to solve this issue for a project where codeblocks are rendered client-side after the code is decrypted.

metonym commented 2 years ago

A recipe for code-splitting is now documented in the README. In addition, a DynamicImport component has been added to each example set-up.

The nice thing about SvelteKit/Vite/Webpack is that code-split the build with zero-configuration. The Rollup example needed a few tweaks to the rollup.config.js.

<script>
  import { onMount } from "svelte";

  let component;
  let styles;

  onMount(async () => {
    component = (await import("svelte-highlight")).HighlightAuto;
    styles = (await import("svelte-highlight/styles/github")).default;
  });
</script>

<svelte:head>
  {#if styles}
    {@html styles}
  {/if}
</svelte:head>

<svelte:component
  this={component}
  langtag
  code={`body {\n  padding: 0;\n  color: red;\n}`}
/>

As a result, the code is split into chunks, which can improve performance.

dynamic-import