January 24, 2021
For this blog, I wanted to parse the blog posts (written in markdown) and also add syntax highlighting to the code blocks so they can have nice readable colors.
I wrote this
parseMarkdown() function to turn raw markdown into HTML with syntax-highlighted code blocks:
First, we import the
Then, we import different Prism "components" that allow it to parse different languages. The full list of components you can import is here.
Then, we tell Marked that we want to handle code highlighting differently. If the code block has a language indicated, like this:
...and Prism is able to parse it (tested by seeing whether it's in
prism.languages - Prism will be able to parse languages that we imported components for), we use
prism.highlight() to syntax-highlight the code. Otherwise, we just return the code itself.
Now, if you look at the outputted HTML from the
parseMarkdown() function, the code blocks are invisibly split up with classes that allow you to use any Prism CSS theme to style them.
A quick favor: was anything I wrote incorrect or misspelled, or do you still have questions? Please use this form to let me know or ask for help!