透過 100 多個技巧的集合學習 Nuxt!

mdc
@nuxtjs/mdc

MDC 超級強化了常規 Markdown,讓您可以編寫與任何 Vue 元件深度互動的文件。

Nuxt MDC

Nuxt MDC

npm versionnpm downloadsLicenseNuxt

MDC 超級強化了常規 Markdown,讓您可以編寫與任何 Vue 元件深度互動的文件。MDC 代表 MarkDown Components(Markdown 元件)。

功能

  • 將 Markdown 語法與 HTML 標籤或 Vue 元件混合使用
  • 解除任何產生的內容包裝 (例如:每個 Markdown 段落新增的 <p>)
  • 使用具有具名插槽的 Vue 元件
  • 支援內聯元件
  • 支援巢狀元件的非同步渲染
  • 將屬性和類別新增至內聯 HTML 標籤

https://content.nuxtjs.org/guide/writing/mdc 了解更多關於 MDC 語法的資訊

!注意 您可以在您的 Nuxt 專案(標準配置)或任何 Vue 專案中使用此套件。

請參閱下方「在您的 Vue 專案中渲染」以取得更多資訊。

安裝

npx nuxi@latest module add mdc

然後,將 @nuxtjs/mdc 新增至您的 nuxt.config.ts 的模組區段

nuxt.config.ts
export default defineNuxtConfig({
  modules: ['@nuxtjs/mdc']
})

就是這樣!您可以在您的 Nuxt 專案中開始撰寫和渲染 markdown 檔案了 ✨

渲染

@nuxtjs/mdc 公開三個元件來渲染 markdown 檔案。

<MDC>

使用 <MDC>,您可以在您的元件/頁面內直接解析和渲染 markdown 內容。此元件會接收原始 markdown,使用 parseMarkdown 函式解析,然後使用 <MDCRenderer> 渲染。

<script setup lang="ts">
const md = `
::alert
Hello MDC
::
`
</script>

<template>
  <MDC :value="md" tag="article" />
</template>

請注意,::alert 將使用 components/global/Alert.vue 元件。

<MDCRenderer>

此元件會接收 parseMarkdown 函式的結果並渲染內容。例如,這是 瀏覽器區段中範例程式碼的擴展版本,它使用 MDCRenderer 來渲染已解析的 markdown。

mdc-test.vue
<script setup lang="ts">
import { parseMarkdown } from '@nuxtjs/mdc/runtime'

const { data: ast } = await useAsyncData('markdown', () => parseMarkdown('::alert\nMissing markdown input\n::'))
</script>

<template>
  <MDCRenderer :body="ast.body" :data="ast.data" />
</template>

<MDCSlot>

此元件是 Vue 的 <slot/> 元件的替代品,專為 MDC 設計。使用此元件,您可以渲染元件的子元件,同時移除一個或多個包裝元素。在以下範例中,Alert 元件會接收文字及其預設插槽(子元件)。但是,如果元件使用一般的 <slot/> 渲染此插槽,它會在文字周圍渲染一個 <p> 元素。

markdown.md
::alert
This is an Alert
::
Alert.vue
<template>
  <div class="alert">
    <!-- Slot will render <p> tag around the text -->
    <slot />
  </div>
</template>

將每個文字包裝在段落中是 markdown 的預設行為。MDC 並非為了破壞 markdown 行為而生;相反地,MDC 的目標是讓 markdown 功能更強大。在此範例和所有類似的情況中,您可以使用 <MDCSlot /> 來移除不需要的包裝器。

Alert.vue
<template>
  <div class="alert">
    <!-- MDCSlot will only render the actual text without the wrapping <p> -->
    <MDCSlot unwrap="p" />
  </div>
</template>

Prose 元件

Prose 元件是一系列將會渲染而不是常規 HTML 標籤的元件。例如,@nuxtjs/mdc 會渲染 <ProseP> 元件而不是渲染 <p> 標籤。當您想要將額外的功能新增至您的 markdown 檔案時,這非常有用。例如,您可以在程式碼區塊中新增一個 copy 按鈕。

您可以透過在 nuxt.config.ts 中將 prose 選項設定為 false 來停用 prose 元件。或者擴展 prose 元件的對應來新增您自己的元件。

nuxt.config.ts
export default defineNuxtConfig({
  modules: ['@nuxtjs/mdc'],
  mdc: {
    components: {
      prose: false, // Disable predefined prose components
      map: {
        p: 'MyCustomPComponent'
      }
    }
  }
})

以下是可用的 prose 元件清單

標籤元件來源描述
p<ProseP>ProseP.vue段落
h1<ProseH1>ProseH1.vue標題 1
h2<ProseH2>ProseH2.vue標題 2
h3<ProseH3>ProseH3.vue標題 3
h4<ProseH4>ProseH4.vue標題 4
h5<ProseH5>ProseH5.vue標題 5
h6<ProseH6>ProseH6.vue標題 6
ul<ProseUl>ProseUl.vue無序清單
ol<ProseOl>ProseOl.vue有序清單
li<ProseLi>ProseLi.vue清單項目
blockquote<ProseBlockquote>ProseBlockquote.vue區塊引述
hr<ProseHr>ProseHr.vue水平線
pre<ProsePre>ProsePre.vue預先格式化的文字
code<ProseCode>ProseCode.vue程式碼區塊
table<ProseTable>ProseTable.vue表格
thead<ProseThead>ProseThead.vue表格標題
tbody<ProseTbody>ProseTbody.vue表格內文
tr<ProseTr>ProseTr.vue表格列
th<ProseTh>ProseTh.vue表格標頭
td<ProseTd>ProseTd.vue表格資料
a<ProseA>ProseA.vue錨點連結
img<ProseImg>ProseImg.vue圖片
em<ProseEm>ProseEm.vue強調
strong<ProseStrong>ProseStrong.vue粗體

解析 Markdown

Nuxt MDC 公開一個方便的助手來解析 MDC 檔案。您可以從 @nuxtjs/mdc/runtime 匯入 parseMarkdown 函式,並使用它來解析使用 MDC 語法撰寫的 markdown 檔案。

Node.js

// server/api/parse-mdc.ts
import { parseMarkdown } from '@nuxtjs/mdc/runtime'

export default eventHandler(async () => {
  const mdc = [
    '# Hello MDC',
    '',
    '::alert',
    'This is an Alert',
    '::'
  ].join('\n')

  const ast = await parseMarkdown(mdc)

  return ast
})

瀏覽器

parseMarkdown 函式是一個通用的助手,您也可以在瀏覽器中使用它,例如在 Vue 元件內。

<script setup lang="ts">
import { parseMarkdown } from '@nuxtjs/mdc/runtime'

const { data: ast } = await useAsyncData('markdown', () => parseMarkdown('::alert\nMissing markdown input\n::'))
</script>

<template>
  <MDCRenderer :body="ast.body" :data="ast.data" />
</template>

選項

parseMarkdown 助手也接受選項作為第二個引數,以控制解析器的行為。(查看 MDCParseOptions 介面↗︎)。

名稱預設值描述
remark.plugins{}註冊/設定解析器的 remark 外掛程式。
rehype.options{}設定 remark-rehype 選項。
rehype.plugins{}註冊/設定解析器的 rehype 外掛程式。
highlightfalse控制程式碼區塊是否應反白顯示。您也可以提供自訂的反白顯示器。
toc.depth2包含在目錄中的最大標題深度。
toc.searchDepth2要搜尋標題的巢狀標籤最大深度。

查看 MDCParseOptions 類型↗︎

設定

您可以透過在 nuxt.config.js 中提供 mdc 屬性來設定模組;以下是預設選項

import { defineNuxtConfig } from 'nuxt/config'

export default defineNuxtConfig({
  modules: ['@nuxtjs/mdc'],
  mdc: {
    remarkPlugins: {
      plugins: {
        // Register/Configure remark plugin to extend the parser
      }
    },
    rehypePlugins: {
      options: {
        // Configure rehype options to extend the parser
      },
      plugins: {
        // Register/Configure rehype plugin to extend the parser
      }
    },
    headings: {
      anchorLinks: {
        // Enable/Disable heading anchor links. { h1: true, h2: false }
      }
    },
    highlight: false, // Control syntax highlighting
    components: {
      prose: false, // Add predefined map to render Prose Components instead of HTML tags, like p, ul, code
      map: {
        // This map will be used in `<MDCRenderer>` to control rendered components
      }
    }
  }
})

查看 ModuleOptions 類型↗︎


渲染巢狀非同步元件

MDCRenderer 也支援渲染*巢狀*非同步元件,方法是等待其樹狀結構中的任何子元件解析其頂層 async setup()

此行為允許渲染非同步 MDC 區塊元件(例如,透過 defineAsyncComponent),以及引入本身內部利用 MDCRenderer 來渲染 markdown,然後才允許父元件解析的元件。

為了讓父 MDCRenderer 元件正確等待子非同步元件解析

  1. 子元件中的所有功能**必須**在具有頂層 await 的非同步設定函式中執行(如果子元件中不需要非同步/await 行為,例如不擷取資料,則元件將正常解析)。
  2. 子元件的 template 內容**應**使用內建的 Suspense 元件包裝,並將 suspensible prop 設定為 true
    <template>
      <Suspense suspensible>
        <pre>{{ data }}</pre>
      </Suspense>
    </template>
    
    <script setup>
    const { data } = await useAsyncData(..., {
      immediate: true, // This is the default, but is required for this functionality
    })
    </script>
    

    在 Nuxt 應用程式中,這表示在任何 useAsyncDatauseFetch 呼叫上設定 immediate: false 都會*阻止*父 MDCRenderer 等待,而且父元件可能會在子元件完成渲染之前解析,導致水合錯誤或內容遺失。

簡單範例:非同步元件

您的巢狀 MDC 區塊元件可以在其生命週期中利用頂層 async setup() 作為一部分,例如在允許父元件解析之前等待資料擷取。

請參閱遊樂場中的程式碼 AsyncComponent 元件作為範例,並查看實際行為,請執行 pnpm dev 並導覽至 /async-components 路由以查看遊樂場。

進階範例:MDC「程式碼片段」

為了展示這些巢狀非同步區塊元件的功能有多強大,您可以允許使用者在您的專案中定義 markdown 文件子集,這些文件將在父文件中用作可重複使用的「程式碼片段」。

您會在您的專案中建立一個自訂區塊元件,該元件會處理從 API 擷取程式碼片段 markdown 內容、使用 parseMarkdown 來取得 ast 節點,並將其渲染在其自己的 MDCMDCRenderer 元件中。

請參閱遊樂場中的程式碼 PageSnippet 元件作為範例,並查看實際行為,請執行 pnpm dev 並導覽至 /async-components/advanced 路由以查看遊樂場。

處理遞迴

如果您的專案實作「可重複使用程式碼片段」類型的方法,您可能會想要防止使用遞迴程式碼片段,也就是說,巢狀 MDCRenderer 嘗試在其元件樹狀結構中的某處載入另一個具有相同內容的子元件(表示匯入自身),而您的應用程式將會陷入無限迴圈。

其中一種解決方法是利用 Vue 的 provide/inject 來傳遞已渲染「程式碼片段」的歷史記錄,以便子元件能正確判斷是否被遞迴呼叫,並停止鏈結。這可以與在呼叫 parseMarkdown 函式後解析 ast 文件節點結合使用,以在 DOM 中渲染內容之前,從 ast 中移除遞迴的節點樹。

關於如何使用此模式來防止無限迴圈和遞迴的範例,請參閱 Playground 中的 PageSnippet 元件中的程式碼。


在您的 Vue 專案中渲染

在一般(非 Nuxt)Vue 專案中,也可以使用 <MDCRenderer> 元件與一些匯出的套件工具。

若要在標準的 Vue 專案中實作,請依照以下指示進行。

安裝套件

依照上述的安裝指示,忽略將 Nuxt 模組新增至 nuxt.config.ts 檔案的步驟。

樁接 Nuxt 模組匯入

由於您未使用 Nuxt,因此您需要在 Vue 專案的 Vite 設定檔中樁接一些模組的匯入。這是為了避免當模組嘗試存取 Nuxt 特定的匯入時發生錯誤。

在您的 Vue 專案根目錄中建立一個新檔案,例如 stub-mdc-imports.js,並新增以下內容

// stub-mdc-imports.js
export default {}

接下來,更新您的 Vue 專案的 Vite 設定檔 (例如 vite.config.ts),將模組的匯入別名指向樁接檔案

import { defineConfig } from 'vite'
import path from 'path'

export default defineConfig({
  resolve: {
    alias: {
      '#mdc-imports': path.resolve(__dirname, './stub-mdc-imports.js'),
      '#mdc-configs': path.resolve(__dirname, './stub-mdc-imports.js'),
    }
  }
})

使用方法

接下來,讓我們建立一個新的 Vue composable 來處理 Markdown 內容的解析,以及使用 Shiki 為程式碼區塊新增語法高亮。

// composables/useMarkdownParser.ts
// Import package exports
import {
  createMarkdownParser,
  rehypeHighlight,
  createShikiHighlighter,
} from '@nuxtjs/mdc/runtime'
// Import desired Shiki themes and languages
import MaterialThemePalenight from 'shiki/themes/material-theme-palenight.mjs'
import HtmlLang from 'shiki/langs/html.mjs'
import MdcLang from 'shiki/langs/mdc.mjs'
import TsLang from 'shiki/langs/typescript.mjs'
import VueLang from 'shiki/langs/vue.mjs'
import ScssLang from 'shiki/langs/scss.mjs'
import YamlLang from 'shiki/langs/yaml.mjs'

export default function useMarkdownParser() {
  let parser: Awaited<ReturnType<typeof createMarkdownParser>>

  const parse = async (markdown: string) => {
    if (!parser) {
      parser = await createMarkdownParser({
        rehype: {
          plugins: {
            highlight: {
              instance: rehypeHighlight,
              options: {
                // Pass in your desired theme(s)
                theme: 'material-theme-palenight',
                // Create the Shiki highlighter
                highlighter: createShikiHighlighter({
                  bundledThemes: {
                    'material-theme-palenight': MaterialThemePalenight,
                  },
                  // Configure the bundled languages
                  bundledLangs: {
                    html: HtmlLang,
                    mdc: MdcLang,
                    vue: VueLang,
                    yml: YamlLang,
                    scss: ScssLang,
                    ts: TsLang,
                    typescript: TsLang,
                  },
                }),
              },
            },
          },
        },
      })
    }
    return parser(markdown)
  }

  return parse
}

現在,將我們剛建立的 useMarkdownParser composable 以及匯出的類型介面匯入您的主專案的 Vue 元件中,並利用它們來處理原始的 Markdown 並初始化 <MDCRenderer> 元件。

<script setup lang="ts">
import { onBeforeMount, ref, watch } from 'vue'
// Import package exports
import MDCRenderer from '@nuxtjs/mdc/runtime/components/MDCRenderer.vue'
import type { MDCParserResult } from '@nuxtjs/mdc'
import useMarkdownParser from './composables/useMarkdownParser';

const md = ref(`
# Just a Vue app

This is markdown content rendered via the \`<MDCRenderer>\` component, including MDC below.

::alert
Hello MDC
::

\`\`\`ts
const a = 1;
\`\`\`
`);

const ast = ref<MDCParserResult | null>(null)
const parse = useMarkdownParser()

onBeforeMount(async () => {
  ast.value = await parse(md.value)
})
</script>

<template>
  <Suspense>
    <MDCRenderer v-if="ast?.body" :body="ast.body" :data="ast.data" />
  </Suspense>
</template>

貢獻

您可以使用 StackBlitz 線上深入了解此模組

Edit @nuxtjs/mdc

或在本機上

  1. 複製此儲存庫
  2. 使用 pnpm install 安裝相依性
  3. 使用 pnpm dev 啟動開發伺服器

授權條款

MIT 授權條款

版權所有 (c) NuxtLabs