Showing Markdown Content as HTML in Vue

In this post, I’ll demonstrate how to convert a markdown file into HTML in Vue. This is inspired by a YouTube video on creating a Next.js blog using the next-mdx-remote package from Hashicorp. However, I found limited resources for achieving the same in Vue, so I decided to write this for anyone looking to build a blog or content management system with markdown files.

While Vue lacks specialized packages, the original @mdx-js/mdx package provides the necessary support. Converting a markdown file to HTML in Vue is pretty straightforward. It features two functions: compile and run, which transform markdown into HTML and render it as a Vue component.


<script setup lang="ts">
import { compile, run } from '@mdx-js/mdx';
import * as runtime from 'vue/jsx-runtime';

const mdx = `# Hello World`;
const code = await compile(mdx, {  
    jsxImportSource: 'vue',
    outputFormat: 'function-body',
});

const { default: MdxContent } = await run(res, { ...runtime });
</script>

<template>
    <MdxContent />
</template>

To ensure @mdx-js/mdx generates Vue-compatible code, set jsxImportSource to vue and use outputFormat: 'function-body'. This is crucial for proper code generation.

I also created a repo in Stackblitz for those who are interested in the full code. The sample in this link also includes the support of custom components in the markdown, to make it more advanced.