·

How to do syntax highlighting for code blocks in Nuxt?

Published at 2024-06-26 18:15:09Viewed 576 times
Professional article
Please reprint with source link

Do you also want to highlight the code block in your website like other platforms? There are two Javascript libraries that help you acheive syntax highlighting. They are Prism.js and highlight.js. In this tutorial, we will show how to use Prism.js to do syntax highlighting with Nuxt.js.

First, you can use npm to install PrismJS:

npm install prismjs

Next, go to composables directory and create a new file prism.js which looks like:

import Prism from 'prismjs'
import 'prismjs/themes/prism-tomorrow.css' // You can choose other themes

export default Prism

Now, prismJS is successfully configured and you just need to call the function highlightAll() every time you need. For example:

<script lang="ts" setup>
onMounted(()=>{
    Prism.highlightAll()
})

$fetch('https://www.example.com')
.then((res)=>{
    nextTick(()=>{
        Prism.highlightAll()
    })
})
</script>

Moreover, note that with the above configuration, prismJS can only highlight Javascript and a few other languages. Therefore, if you want to highlight more languages, you need to import their components into prism.js one by one. For example, if you want to highlight Typescript:

import Prism from 'prismjs'
import 'prismjs/themes/prism-tomorrow.css' // You can choose other themes
import "prismjs/components/prism-typescript"

export default Prism

If you have a lot of languages that are needed to highlight, then it would be annoying to import all their components to prism.js. To avoid this problem, you can use the Autoloader plugin. However, it is difficult to use prismJS plugins with Nuxt.js. The easiest way to load plugins is to use CDN, which will be explained in our next article.

0 人喜欢

Comments

There is no comment, let's add the first one.

弦圈热门内容

Get connected with us on social networks! Twitter

©2024 Guangzhou Sinephony Technology Co., Ltd All Rights Reserved