Svelte action for lazy loading Prism.js code highlighting languages from remote or local path.
The action uses IntersectionObserver to dynamically render code highlighting. The prism.js language file is lazy loaded when the <code>
element gets visible in the viewport.
$ npm install svelte-prism-action
Include a Prism.js CSS theme in your svelte component or use the <head>
section of your index.html
.
<link
href="https://unpkg.com/[email protected]/themes/prism.css"
rel="stylesheet"
/>
Import prism
from svelte-prism-action
. Add the action to a component with use:prism
. All <code>
elements with a class="language-..."
will get highlighted once they have entered the viewport.
For available language tags see https://prismjs.com/#supported-languages .
HINT If you are writing your codeblocks directly into a svelte component you need to escape special characters (eg. curley brackets). Another way is to wrap the code inside {``}
.
<script>
import { prism } from "svelte-prism-action";
</script>
<!-- add action to component -->
<main use:prism>
<!-- or set some options
<main use:prism={{
componentsUrl: "https://myPathToPrism/components"
}}>
-->
<!-- use in code blocks -->
<pre>
<code class="lang-css">{` <!-- wrap inside {``} if using inside svelte component-->
.bg-gold{
background: gold;
}
`}
</code>
</pre>
<!-- use inline -->
<code class="lang-javascript"
>{`import {prism} from "svelte-prism-action";`}</code
>
</main>
You can use componentsUrl
to set the URL from where to import the Prism.js language files. By default it uses unpkg cdn, but you can use a local resource instead.
To lazy load third party language files (eg. prism-svelte
) or define a different file per language you can use thirdPartyUrls
object with language id
as key and the URL as the value.
You can also change the IntersectionObserver options. For more information on what they do see https://developer.mozilla.org/en-US/docs/Web/API/Intersection_Observer_API#Interfaces .
<main use:prism={{
root: null,
rootMargin: "100px",
threshold: 0,
componentsUrl: "https://unpkg.com/[email protected]/components",
thirdPartyUrls: {
svelte: "https://cdn.jsdelivr.net/npm/[email protected]/index.js"
}
}}>
...
</main>
prism-markup.js
import not finished/* @vite-ignore */
to dynamic import()
.components.js
to reduce package file sizeMIT