metonym/svelte-highlight

Add dynamic import example

Closed this issue · 2 comments

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

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

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