Skip to content

MDC supercharges regular Markdown to write documents interacting deeply with any Vue component.

License

Notifications You must be signed in to change notification settings

Sun-ZhenXing/nuxt-mdc

 
 

Repository files navigation

Nuxt MDC

Nuxt MDC

npm version npm downloads License Nuxt

MDC supercharges regular Markdown to write documents interacting deeply with any Vue component. MDC stands for MarkDown Components.

Features

  • Mix Markdown syntax with HTML tags or Vue components
  • Unwrap any generated content (ex: <p> added by each Markdown paragraph)
  • Use Vue components with named slots
  • Support inline components
  • Add attributes and classes to inline HTML tags

Learn more about the MDC syntax on https://content.nuxtjs.org/guide/writing/mdc

Note

You may utilize this package inside of your Nuxt project (standard configuration) or within any Vue project.

See Rendering in your Vue project below for more information.

Install

npx nuxi@latest module add mdc

Then, add @nuxtjs/mdc to the modules section of your nuxt.config.ts

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

That's it! You can start writing and rendering markdown files in your Nuxt project ✨

Rendering

@nuxtjs/mdc exposes three components to render markdown files.

<MDC>

Using <MDC>, you can parse and render markdown contents right inside your components/pages. This component takes raw markdown, parses it using the parseMarkdown function, and then renders it with <MDCRenderer>.

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

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

Note that ::alert will use the components/global/Alert.vue component.

<MDCRenderer>

This component will take the result of parseMarkdown function and render the contents. For example, this is an extended version of the sample code in the Browser section which uses MDCRenderer to render the parsed markdown.

<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>

This component is a replacement for Vue's <slot/> component, specifically designed for MDC. Using this component, you can render a component's children while removing one or multiple wrapping elements. In the below example, the Alert component receives text and its default slot (children). But if the component renders this slot using the normal <slot/>, it will render a <p> element around the text.

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

It is the default behavior of markdown to wrap every text inside a paragraph. MDC didn't come to break markdown behavior; instead, the goal of MDC is to make markdown powerful. In this example and all similar situations, you can use <MDCSlot /> to remove unwanted wrappers.

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

Prose Components

Prose components are a list of components that will be rendered instead of regular HTML tags. For example, instead of rendering a <p> tag, @nuxtjs/mdc renders a <ProseP> component. This is useful when you want to add extra features to your markdown files. For example, you can add a copy button to your code blocks.

You can disable prose components by setting the prose option to false in nuxt.config.ts. Or extend the map of prose components to add your own components.

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

Here is the list of available prose components:

Tag Component Source Description
p <ProseP> ProseP.vue Paragraph
h1 <ProseH1> ProseH1.vue Heading 1
h2 <ProseH2> ProseH2.vue Heading 2
h3 <ProseH3> ProseH3.vue Heading 3
h4 <ProseH4> ProseH4.vue Heading 4
h5 <ProseH5> ProseH5.vue Heading 5
h6 <ProseH6> ProseH6.vue Heading 6
ul <ProseUl> ProseUl.vue Unordered List
ol <ProseOl> ProseOl.vue Ordered List
li <ProseLi> ProseLi.vue List Item
blockquote <ProseBlockquote> ProseBlockquote.vue Blockquote
hr <ProseHr> ProseHr.vue Horizontal Rule
pre <ProsePre> ProsePre.vue Preformatted Text
code <ProseCode> ProseCode.vue Code Block
table <ProseTable> ProseTable.vue Table
thead <ProseThead> ProseThead.vue Table Head
tbody <ProseTbody> ProseTbody.vue Table Body
tr <ProseTr> ProseTr.vue Table Row
th <ProseTh> ProseTh.vue Table Header
td <ProseTd> ProseTd.vue Table Data
a <ProseA> ProseA.vue Anchor Link
img <ProseImg> ProseImg.vue Image
em <ProseEm> ProseEm.vue Emphasis
strong <ProseStrong> ProseStrong.vue Strong

Parsing Markdown

Nuxt MDC exposes a handy helper to parse MDC files. You can import the parseMarkdown function from @nuxtjs/mdc/runtime and use it to parse markdown files written with MDC syntax.

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
})

Browser

The parseMarkdown function is a universal helper, and you can also use it in the browser, for example inside a Vue component.

<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>

Options

The parseMarkdown helper also accepts options as the second argument to control the parser's behavior. (Checkout MDCParseOptions interface↗︎).

Name Default Description
remark.plugins {} Register / Configure parser's remark plugins.
rehype.options {} Configure remark-rehype options.
rehype.plugins {} Register / Configure parser's rehype plugins.
highlight false Control whether code blocks should highlight or not. You can also provide a custom highlighter.
toc.depth 2 Maximum heading depth to include in the table of contents.
toc.searchDepth 2 Maximum depth of nested tags to search for heading.

Checkout MDCParseOptions types↗︎.

Configurations

You can configure the module by providing the mdc property in your nuxt.config.js; here are the default options:

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
      }
    }
  }
})

Checkout ModuleOptions types↗︎.

Rendering in your Vue project

The <MDCRenderer> component in combination with a few exported package utilities may also be utilized inside a normal (non-Nuxt) Vue project.

To implement in your standard Vue project, follow the instructions below.

Install the package

Follow the install instructions above, ignoring the step of adding the Nuxt module to a nuxt.config.ts file.

Stub Nuxt module imports

Since you're not using Nuxt, you'll need to stub a few of the module's imports in your Vue projects's Vite config file. This is necessary to avoid errors when the module tries to access Nuxt-specific imports.

Create a new file in your Vue project's root directory, such as stub-mdc-imports.js, and add the following content:

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

Next, update your Vue project's Vite config file (e.g. vite.config.ts) to alias the module's imports to the stub file:

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'),
    }
  }
})

Usage

Next, let's create a new Vue composable to handle parsing the markdown content, as well as adding syntax highlighting to code blocks with 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
}

Now import the useMarkdownParser composable we just created along with an exported type interface into your host project's Vue component, and utilize them to process the raw markdown and initialize the <MDCRenderer> component.

<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>

Contributing

You can dive into this module online using StackBlitz:

Edit @nuxtjs/mdc

Or locally:

  1. Clone this repository
  2. Install dependencies using pnpm install
  3. Start the development server using pnpm dev

License

MIT License

Copyright (c) NuxtLabs

About

MDC supercharges regular Markdown to write documents interacting deeply with any Vue component.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • TypeScript 80.3%
  • Vue 19.2%
  • JavaScript 0.5%