As mentioned in this article as well, this site is built with Nuxt.js and Contentful.
Article content is edited in Markdown format via the Contentful editor, then fetched by Nuxt, converted to HTML, and rendered.
However, when the site first launched, the code blocks only had a simple style and felt a bit lacking, so we introduced Prism to enable syntax highlighting.
The usage itself is simple, as shown in Basic Usage, but it took a bit of effort to get it working with Nuxt, so here's a summary of how we did it.
By the way, searching for vue + prism turns up vue-prism-component as well, but it seemed difficult to apply it only to the code blocks within the body text fetched from Contentful, so we didn't use it.
Setting Up Nuxt
Install prismjs with yarn (or npm)
$ yarn add prismjs
Add prismjs to plugins (choose the theme and language to your liking)
// app/plugins/prism.js
import Prism from 'prismjs'
import 'prismjs/themes/prism-tomorrow.css'
export default Prism
// nuxt.config.js
plugins: [
'~/plugins/prism',
],
Load prism on the pages where you want to enable syntax highlighting
// app/pages/articles/_slug.vue
...
<script>
import Prism from '~/plugins/prism'
...
mounted() {
Prism.highlightAll()
},
...
That's it for the Nuxt setup.
At first the syntax highlighting wasn't kicking in and I got stuck, but calling Prism.highlightAll() inside mounted solved it.
Writing Code Blocks in Contentful
When writing a code block in Contentful, you follow Markdown syntax and wrap it above and below with three backticks, but if you specify a language right after the opening three backticks, the corresponding class gets applied.
In the example below, we specify js, so the code element ends up with the class language-js applied.
Any class starting with language- should generally get syntax highlighting as long as it's listed in Prism's Supported languages.
- Markdown source
```js
const posts = await client.getEntries({
content_type: process.env.CTF_BLOG_POST_TYPE_ID,
'fields.slug': slug,
})
```
- Converted HTML
<pre><code class="language-js">
const posts = await client.getEntries({
content_type: process.env.CTF_BLOG_POST_TYPE_ID,
'fields.slug': slug,
})
</code></pre>
Before and After Introducing Prism
- Before
const posts = await client.getEntries({
content_type: process.env.CTF_BLOG_POST_TYPE_ID,
'fields.slug': slug,
})
- After 🎉
const posts = await client.getEntries({
content_type: process.env.CTF_BLOG_POST_TYPE_ID,
'fields.slug': slug,
})
Bonus
If you just want to share a bit of code or post it to a blog, a service called Carbon could also work well.
It's as simple as typing your code into the browser and choosing a theme and language — you can then export it as PNG or SVG, or generate embed code.