You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Nuxt 3.11.2中用@nuxt/content v2.12.1服务端渲染Markdown并支持代码高亮

在Nuxt 3.11.2中用@nuxt/content v2.12.1渲染变量Markdown(SSR+代码高亮)

1. 安装依赖

先安装核心模块及代码高亮所需工具:

npm install @nuxt/content@2.12.1 shiki
# 或使用yarn
yarn add @nuxt/content@2.12.1 shiki

2. 配置Nuxt项目

在nuxt.config.ts中启用content模块并配置代码高亮规则:

export default defineNuxtConfig({
  modules: ['@nuxt/content'],
  content: {
    highlight: {
      theme: 'github-dark', // 可选主题:github-light、nord等
      preload: ['javascript', 'typescript', 'vue'] // 预加载常用语言支持
    }
  }
})

3. 实现LayoutContent组件

在components/LayoutContent.vue中编写组件,完成Markdown编译与SSR渲染:

<template>
  <div class="markdown-render" v-html="compiledHtml"></div>
</template>

<script setup lang="ts">
import type { ParsedContent } from '@nuxt/content/dist/runtime/types'

// 接收外部传入的Markdown字符串
const props = defineProps<{
  markdown: string
}>()

// 服务端编译Markdown为HTML,确保SSR输出
const compiledHtml = await useAsyncData('markdown-compiled', async () => {
  const { parse } = await import('@nuxt/content/dist/runtime/parse')
  const parsed: ParsedContent = await parse(props.markdown, { type: 'markdown' })
  return parsed.body.html
})
</script>

<style scoped>
.markdown-render h1 {
  font-size: 2rem;
  font-weight: 700;
  margin: 1.5rem 0;
}
/* 优化代码块样式 */
pre {
  margin: 1rem 0;
  padding: 1.2rem;
  border-radius: 0.6rem;
  overflow-x: auto;
}
</style>

4. 组件使用示例

在页面或父组件中传入Markdown变量即可渲染:

<template>
  <LayoutContent :markdown="demoMarkdown" />
</template>

<script setup lang="ts">
// 示例Markdown内容,包含代码块
const demoMarkdown = `# Hello World

这是一段带代码高亮的示例内容:

\`\`\`typescript
const sayHi = (name: string) => {
  console.log(\`Hi, \${name}!\`)
}
sayHi('Nuxt Content')
\`\`\`
`
</script>

核心说明

  • SSR保障:通过useAsyncData在服务端完成Markdown编译,直接输出渲染后的HTML,完全满足SEO需求。
  • 代码高亮:依托@nuxt/content内置的shiki引擎,配置主题和预加载语言后,代码块会自动生成高亮样式。
  • 安全提示:若Markdown内容来自用户输入,建议额外引入dompurify对编译后的HTML进行XSS过滤。

内容的提问来源于stack exchange,提问作者YousefHusain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 05:00:03