Javascript is required
·
5 min read

How to Create a Custom Code Block With Nuxt Content v2

How to Create a Custom Code Block With Nuxt Content v2 Image

Code blocks are essential for blogs about software development. In this article, I want to show you how can define a custom code block component in Nuxt Content v2 with the following features:

  • Custom styling for code blocks inside Markdown files
  • Show language name (if available)
  • Show file name (if available)
  • Show a "Copy Code" button

Nuxt Content v2

Nuxt Content v2 is a Nuxt 3 module that reads local files from the /content directory in your project. It supports .md, .yml, .csv and .json files. Additionally, it's possible to use Vue components in Markdown with the MDC Syntax.

Setup Nuxt App

First, let's start a new Nuxt Content project with:

bash
npx nuxi init nuxt-custom-code-blocks -t content

Then we need to install the dependencies in the nuxt-custom-code-blocks folder:

bash
yarn install

Now we can start the Nuxt content app in development mode:

bash
yarn dev

A browser window should automatically open for http://localhost:3000. Alternatively, you can start playing with Nuxt Content in your browser using StackBlitz or CodeSandbox.

The following StackBlitz sandbox demonstrates the application we create in this article:

Custom Prose Component

Prose represents the HTML tags output from the Markdown syntax in Nuxt Content. Nuxt Content provides a Vue component for each HTML tag like links, title levels, etc.

It's possible to override these Vue components, which is precisely what we'll do to create a custom code block component.

To customize a Prose component, we have to perform these steps:

  • Check out the original component sources.
  • Use the same props.
  • Name it the same in our components/content/ directory.

In our example, we want to override ProseCode, which is Nuxt Content's default Vue component to render code blocks in Markdown files.

This component accepts the following props:

  • code: the provided code as a string
  • language: the provided language name
  • filename: the provided filename
  • highlights: a list of highlighted line numbers

Let's take a look at how we can set these values in a Markdown file:

1```js [src/index.js] {1, 2-3}
2  const a = 4;
3  const b = a + 3;
4  const c  = a * b;
5  ```

In the above example:

  • js is the value passed to the language prop
  • src/index.js is the value passed to the filename prop
  • [1, 2, 3] is the value passed to the highlights prop

To override the component, we create ProseCode.vue in the components/content directory and use the exact same props that are defined in the default component:

1<template>
2  <slot />
3</template>
4
5<script setup lang="ts">
6const props = withDefaults(
7  defineProps<{
8    code?: string
9    language?: string | null
10    filename?: string | null
11    highlights?: Array<number>
12  }>(),
13  { code: '', language: null, filename: null, highlights: [] }
14)
15</script>

Now we can customize this component however we want.

Style Container

First, we want to style the container that includes the code. Therefore, we wrap the <slot /> in a div and style it:

1<template>
2  <div class="container">
3    <slot />
4  </div>
5</template>
6
7<style scoped>
8.container {
9  background: #1e1e1e;
10  position: relative;
11  margin-top: 1rem;
12  margin-bottom: 1rem;
13  overflow: hidden;
14  border-radius: 0.5rem;
15}
16</style>

Let's take a look at our custom code block:

Styled Code Block Container

Show Language

Next, we want to show the name of the language on the top right, if it is available.

1<template>
2  <div class="container">
3    <span v-if="languageText" :style="{ background: languageBackground, color: languageColor }" class="language-text">
4      {{ languageText }}
5    </span>
6    <slot />
7  </div>
8</template>
9
10<script setup lang="ts">
11const props = withDefaults(
12  defineProps<{
13    code?: string
14    language?: string | null
15    filename?: string | null
16    highlights?: Array<number>
17  }>(),
18  { code: '', language: null, filename: null, highlights: [] }
19)
20
21const languageMap: Record<string, { text: string; color: string; background: string }> = {
22  vue: {
23    text: 'vue',
24    background: '#42b883',
25    color: 'white',
26  },
27  js: {
28    text: 'js',
29    background: '#f7df1e',
30    color: 'black',
31  },
32}
33
34const languageText = computed(() => (props.language ? languageMap[props.language]?.text : null))
35const languageBackground = computed(() => (props.language ? languageMap[props.language]?.background : null))
36const languageColor = computed(() => (props.language ? languageMap[props.language]?.color : null))
37</script>
38
39<style scoped>
40.container {
41  background: #1e1e1e;
42  padding-top: 1em;
43}
44
45.language-text {
46  position: absolute;
47  top: 0;
48  right: 1em;
49  padding: 0.25em 0.5em;
50  font-size: 14px;
51  text-transform: uppercase;
52  border-bottom-right-radius: 0.25em;
53  border-bottom-left-radius: 0.25em;
54}
55</style>

We define a map called languageMap that contains the displayed text, the CSS background, and text color for each programming language. We style the span tag that renders the language inside our template based on this map and the provided language prop:

Code block with language name

Show File Name

Next, we want to show the file's name on the top left, if it is available:

1<template>
2  <div class="container">
3    <span v-if="filename" class="filename-text">
4      {{ filename }}
5    </span>
6    <slot />
7  </div>
8</template>
9
10<style scoped>
11.filename-text {
12  position: absolute;
13  top: 0;
14  left: 1em;
15  padding: 0.25em 0.5em;
16  color: white;
17  font-size: 14px;
18}
19</style>

The result looks like this:

Code block with file name

Add Copy Code Button

Finally, we want to show a button that copies the code to the clipboard. Therefore, we use the useClipboard composable from VueUse:

1<template>
2  <div class="container">
3    <slot />
4    <div class="bottom-container">
5      <div class="copy-container">
6        <span class="copied-text" v-if="copied">Copied code!</span>
7        <button @click="copy(code)">Copy Code</button>
8      </div>
9    </div>
10  </div>
11</template>
12
13<script setup lang="ts">
14import { useClipboard } from '@vueuse/core'
15
16const { copy, copied, text } = useClipboard()
17</script>
18
19<style scoped>
20.bottom-container {
21  display: flex;
22  justify-content: flex-end;
23}
24
25.copy-container {
26  display: flex;
27}
28
29.copied-text {
30  margin-right: 1em;
31}
32</style>

Let's take a look at the final result with language & file name, copy code button, and line highlighting:

Final custom code block

Conclusion

Custom code blocks are essential for my blog as my blog posts contain a lot of code snippets. Features like copy code or line highlighting provide excellent value to my readers, and it is straightforward to add such features by creating a custom code block component in Nuxt Content v2.

The source code of this demo is available at GitHub or as StackBlitz sandbox.

You can expect more Nuxt 3 posts in the following months as I plan to blog about interesting topics that I discover while rewriting my portfolio website.

If you liked this article, follow me on Twitter to get notified about new blog posts and more content from me.

Alternatively (or additionally), you can also subscribe to my newsletter.

I will never share any of your personal data. You can unsubscribe at any time.

If you found this article helpful.You will love these ones as well.
Focus & Code Diff in Nuxt Content Code Blocks Image

Focus & Code Diff in Nuxt Content Code Blocks

A Comprehensive Guide to Data Fetching in Nuxt 3 Image

A Comprehensive Guide to Data Fetching in Nuxt 3

Use Shiki to Style Code Blocks in HTML Emails Image

Use Shiki to Style Code Blocks in HTML Emails

How I Replaced Revue With a Custom-Built Newsletter Service Using Nuxt 3, Supabase, Serverless, and Amazon SES Image

How I Replaced Revue With a Custom-Built Newsletter Service Using Nuxt 3, Supabase, Serverless, and Amazon SES