Prismjs is a syntax highlighting library in Javascript. Most of the examples provided are a bit difficult to work with in a Svelte application.
<script>
import Prism from 'prismjs';
import 'prismjs/components/prism-sql.js'
import 'prismjs/components/prism-plsql.js'
import 'prismjs/themes/prism.css';
let codeText = 'CREATE TABLE FOO(\nc1 int,\n c2 int\n);
</script>
<div style="white-space: pre">
{@html Prism.highlight(codeText, Prism.languages.sql, 'sql')}
</div>
npm install prismjs
The core import is:
import Prism from 'prismjs';
However, you will need to additionally import any non-default languages and CSS.
First check out the supported languages here. There are four default languages, which you do not need to import: markup, css, clike, and javascript.
In my case, I wanted to display SQL and well as PL/SQL. So in the supported languages link, I found that SQL has the code sql
and PL/SQL has the code plsql
. Import them like this:
import 'prismjs/components/prism-sql.js'
import 'prismjs/components/prism-plsql.js'
For example if you need to add syntax highlighting for GoLang, the code is go
, and the import would be:
import 'prismjs/components/prism-go.js'
In addition, you have to import a CSS file, otherwise you will not get color coding:
import 'prismjs/themes/prism.css';
<div style="white-space: pre">
{@html Prism.highlight(codeText, Prism.languages.sql, 'sql')}
</div>
You have to use white-space: pre
or white-space: pre-wrap
, otherwise any new lines will not work.
The Svelte @html
keyword will be used to render the HTML that is created by Prism.highlight
If you are using a different language, you need to change the code. For example:
{@html Prism.highlight(codeText, Prism.languages.plsql, 'plsql')}
{@html Prism.highlight(codeText, Prism.languages.go, 'go')}