Make sure it is rendering on the server side for SEO reasons.
<script setup lang="ts">
const markdown = "# hello world"
</script>
<template>
<LayoutContent>
<!-- renders "markdown" here -->
</LayoutContent>
</template>
I wanted to compile "markdown" into html and render it inside a LayoutContent component.
In addition, I want it to support code highlight.
Step 1: Install the packages markdown-it
and highlight.js
by running the following command in your terminal:
npm install -D markdown-it highlight.js
Step 2: Update your nuxt.config.ts
file by enabling support for .server.vue
extensions, which enables Server-Side Rendering. To achieve this, add the experimental property with the value componentIslands: true
.
export default defineNuxtConfig({
// ...
experimental: {
componentIslands: true,
},
})
Step 3: Create a new component named HighlightedMarkdown.server.vue
and save it in the components
directory, then set the content of the component to the following:
<script setup lang="ts">
import markdownit from 'markdown-it'
import hljs from 'highlight.js'
interface PropsType {
markdown: string
}
const { markdown } = defineProps<PropsType>()
const md = markdownit({
highlight(str, lang) {
if (lang && hljs.getLanguage(lang)) {
try {
return hljs.highlight(str, { language: lang }).value
}
catch (__) {}
}
return '' // use external default escaping
},
})
const html = md.render(markdown)
</script>
<template>
<div class="prose prose-lg" v-html="html" />
</template>
Step 4: To enable code highlighting, you can install a theme CSS file. You can find more information here.
If you're using tailwindcss in your application, you'll need to include the @tailwindcss/typography plugin. To add the plugin, follow these simple steps:
npm install -D @tailwindcss/typography
tailwind.config.ts
file, import the plugin:import tailwindTypography from '@tailwindcss/typography'
plugins
inside your tailwind.config.ts
file:plugins: [tailwindTypography()]
Now that all the necessary steps have been completed, you can easily add the HighlightedMarkdown
component wherever you need it in your project.
<script setup lang="ts">
const markdown = `
# Heading 1
## Heading 2
### Heading 3
#### Heading 4
\`\`\`javascript
function myFunction () {
console.log("Hello World")
}
\`\`\`
`
</script>
<template>
<LayoutContent>
<HighlightedMarkdown :markdown="markdown" />
</LayoutContent>
</template>