0
Fork 0
mirror of https://github.com/withastro/astro.git synced 2024-12-23 21:53:55 -05:00
astro/components/Prism.astro
Matthew Phillips 72ae661e9e
Add support for syntax highlighting of code blocks (#65)
* Add support for syntax highlighting of code blocks

* Escape usage of backtick strings

* Add workspace root for snowpack

* Use prismjs/components as an external module
2021-04-08 15:17:00 -04:00

42 lines
No EOL
871 B
Text

---
import Prism from 'prismjs';
import { addAstro } from '../astro-prism/index.mjs';
import * as loadLanguages from 'prismjs/components/';
export let lang;
export let code;
const languageMap = new Map([
['ts', 'typescript']
]);
if(lang == null) {
console.warn('Prism.astro: No language provided.');
}
const ensureLoaded = lang => {
if(!Prism.languages[lang]) {
loadLanguages([lang]);
}
};
if(languageMap.has(lang)) {
ensureLoaded(languageMap.get(lang));
} else if(lang === 'astro') {
ensureLoaded('typescript');
addAstro(Prism);
} else {
ensureLoaded(lang);
}
if(!Prism.languages[lang]) {
console.warn(`Unable to load the language: ${lang}`);
}
const grammar = Prism.languages[lang];
let html = Prism.highlight(code, grammar, lang);
let className = `language-${lang}`;
---
<pre class={className}><code class={className}>{html}</code></pre>