Markdown 渲染方案选型 
1. 常见 Markdown 渲染方案 
在 Web 开发中,选择合适的 Markdown 渲染方案对于内容展示至关重要。本文将介绍几种常见的 Markdown 渲染方案及其适用场景。
2. markdown-it 生态 
2.1 核心库 
markdown-it 是一个高性能的 Markdown 解析器,具有插件化架构:
bash
npm install markdown-it @types/markdown-it2.2 常用插件 
- markdown-it-container:自定义容器块
- highlight.js:代码高亮支持
- markdown-it-anchor:标题锚点
- markdown-it-toc-done-right:目录生成
2.3 基本使用 
typescript
import MarkdownIt from 'markdown-it'
import highlightjs from 'highlight.js'
const md = new MarkdownIt({
  html: true,
  linkify: true,
  typographer: true,
  highlight: function (str, lang) {
    if (lang && highlightjs.getLanguage(lang)) {
      try {
        return highlightjs.highlight(str, { language: lang }).value
      } catch (__) {}
    }
    return ''
  }
})
const html = md.render('# Hello World')3. Remark 生态 
3.1 简介 
Remark 是基于 unified 生态系统的 Markdown 处理器,支持插件和转换管道:
bash
npm install remark remark-html remark-rehype3.2 特点 
- 基于 AST(抽象语法树)处理
- 丰富的插件生态
- 支持自定义转换
- 与 rehype(HTML 处理器)无缝集成
3.3 使用示例 
javascript
import { unified } from 'unified'
import remarkParse from 'remark-parse'
import remarkRehype from 'remark-rehype'
import rehypeStringify from 'rehype-stringify'
const file = await unified()
  .use(remarkParse)
  .use(remarkRehype)
  .use(rehypeStringify)
  .process('# Hello World')
console.log(String(file))4. Metalsmith 
Metalsmith 是一个静态网站生成器,可以用于构建基于 Markdown 的文档站点:
bash
npm install metalsmith metalsmith-markdown适用于需要构建完整静态站点的场景。
5. MDC/MDX 方案 
5.1 MDX 
MDX 允许在 Markdown 中使用 JSX 组件:
bash
npm install @mdx-js/mdx @mdx-js/react5.2 Nuxt MDC 
Nuxt MDC 是 Nuxt 3 的 Markdown 组件方案:
bash
npm install @nuxtjs/mdc项目地址:https://github.com/nuxt-modules/mdc
6. Nuxt 集成方案 
6.1 @nuxtjs/markdownit 
在 Nuxt 2 中常用的 Markdown 渲染模块:
bash
npm install @nuxtjs/markdownit配置 nuxt.config.js:
javascript
export default {
  modules: ['@nuxtjs/markdownit'],
  markdownit: {
    preset: 'default',
    linkify: true,
    breaks: true,
    use: [
      'markdown-it-container',
      'markdown-it-attrs'
    ]
  }
}6.2 Nuxt 3 支持 
Nuxt 3 中的 Markdown 渲染方案:
- 使用 @nuxtjs/mdc模块(推荐)
- 使用 Nuxt Content 模块
- 自定义集成 markdown-it 或 remark
参考:
- https://github.com/nuxt-community/markdownit-module/issues/47
- https://stackoverflow.com/questions/75743246/nuxt3-how-to-display-markdown-content-as-html-tags
7. 方案选型建议 
根据不同的使用场景,选择合适的方案:
7.1 简单博客或文档 
推荐使用 markdown-it:
- 轻量级,易于集成
- 插件丰富
- 性能优秀
7.2 React/Next.js 项目 
推荐使用 MDX:
- 支持组件化
- 与 React 生态无缝集成
- 灵活度高
7.3 Nuxt 项目 
推荐使用 Nuxt Content 或 @nuxtjs/mdc:
- 官方支持
- 与 Nuxt 生态集成好
- 自动路由生成
7.4 复杂文档站点 
推荐使用 VitePress 或 Docusaurus:
- 开箱即用
- 主题丰富
- SEO 友好
8. 参考资料 
以下是一些有用的参考资源:
- https://github.com/markdown-it/markdown-it - markdown-it 官方仓库
- https://github.com/remarkjs/remark - Remark 官方仓库
- https://mdxjs.com/ - MDX 官方文档
- https://github.com/nuxt-community/markdownit-module/issues/47 - Nuxt 3 Markdown 支持讨论
- https://github.com/nuxt-community/markdownit-module/issues/67 - Nuxt Markdown 集成讨论
- https://segmentfault.com/a/1190000043619965 - Markdown 渲染方案对比