Switch Syntax Highlighting Theme In @nuxt/content

  • Home
  • -
  • Blog
  • -
  • Post
  • -
  • SyntaxHighlightingThemeNuxtContent
2021 . Nov . 21 / Web DevelopmentHow to Blog

The default configuration

When using @nuxt/content syntax highlighting we can use the Nuxt configuration file to set the theme for our highlighted code:

nuxt.config.js
export default {
    // ...
    content: {
        markdown: {
            prism: {
                theme: 'prism-themes/themes/prism-vsc-dark-plus.css'
            }
        }
    }
};

The downside of this approach is that is not possible to change the theme on the fly and we are limited to only one theme.

Switching themes

Now, what if we want to change the theme according to some configuration, e.g. dark/light theme switching?

A way to do it is setting the <link rel="stylesheet" href="theme.css" /> tag manually. So, first, we have to download the css file of the theme. Or install the prism-themes npm package and get the css from the node_modules/prism-themes/themes directory. Now, we have to put the css inside the static directory.

Next, the Nuxt configuration file should look like this to avoid the default theme:

nuxt.config.js
export default {
    // ...
    content: {
        markdown: {
            prism: {
                theme: false
            }
        }
    }
};

Having done that, a way to set the link tag is using the head() method of a Vue component that is going to manage the theme, just like this:

template : Theme.vue
<button @click="isDarkTheme = !isDarkTheme">Switch Theme</button>
script : Theme.vue
export default {
    data() {
        return {
            isDarkTheme: false
        };
    },

    head() {
        return {
            link: [
                {
                    rel: 'stylesheet',
                    href: `/${this.isDarkTheme ? 'dark-theme.css' : 'ligth-theme.css'}`
                }
            ]
        };
    }
};

This way the theme can be changed on the fly, and we are not limited to only one theme.

Comments
If you have any doubt or question, or know how to improve this post, please feel free to write a comment.