Compiling Markdown into browser modules with Vite
Build a Vite transform plugin that exposes Markdown front matter and HTML as a typed module, then verify hot updates and production output.
I wanted a documentation page to import
.mdfiles directly. A small Vite transform plugin turns the source into a JavaScript module with named metadata and HTML exports, plus a renderer for the client.
Making documentation an application import
A component can work with Markdown as a module instead of fetching it separately and parsing it in every browser. My target API exposes the rendered content and front matter, so a page can render the article and also use its title in navigation.
1
2
// Module imports used by the frontend
import GuideDoc, { frontmatter, html } from './docs/architecture.md';
Vite does not compile Markdown to a component by default. A plugin can own that file type and let the normal module graph track who imports it. The transformation also gives production a chance to bundle the result as JavaScript.
From document source to ES module
flowchart TD
RawFile["Request Markdown"] --> FilterId{"id.endsWith('.md')<br/>Check extension"}
FilterId -- "No" --> PassThrough["Pass through"]
FilterId -- "Yes" --> ExtractFM["Extract front matter"]
ExtractFM --> ParseMD["Parse Markdown"]
ParseMD --> Codegen["Emit JavaScript exports"]
Codegen --> ReturnCode["Return ES module"]
ReturnCode --> ClientRender["Render the update"]
The hot path should reject unrelated IDs first. A matching document can then be broken into its leading YAML-style front matter and its body. The sample renderer converts Markdown-style elements into HTML. Finally, the plugin returns JavaScript source that exports the metadata, the HTML string, and the renderer.
This is the same transform(code, id) phase that other plugins use for individual source files. The ID can carry query parameters when a consumer requests another handling mode. Filter the exact mode you intend instead of accidentally changing imports such as ?raw. Vite Plugin API
Implementing and typing the compiler
The sample uses a deliberately small parser for basic front matter and Markdown formatting. That makes the code generation easy to trace. For documents with rich YAML, code fences, or CommonMark edge cases, use a maintained parser such as markdown-it or marked.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
// plugins/vite-plugin-markdown-compiler.ts
import type { Plugin } from 'vite';
export interface MarkdownPluginOptions {
sanitize?: boolean;
}
export function markdownCompilerPlugin(options: MarkdownPluginOptions = {}): Plugin {
// Helpers for front matter and basic Markdown
const parseMarkdown = (rawContent: string) => {
let frontmatter: Record<string, any> = {};
let content = rawContent;
// Match the front matter delimiters
const fmRegex = /^---\r?\n([\s\S]*?)\r?\n---\r?\n/;
const fmMatch = rawContent.match(fmRegex);
if (fmMatch) {
const rawFm = fmMatch[1];
content = rawContent.slice(fmMatch[0].length);
// Parse simple YAML key-value pairs
rawFm.split('\n').forEach((line) => {
const colonIdx = line.indexOf(':');
if (colonIdx !== -1) {
const key = line.slice(0, colonIdx).trim();
let val: any = line.slice(colonIdx + 1).trim();
// Read quoted values and numbers
if (val.startsWith('"') && val.endsWith('"')) val = val.slice(1, -1);
else if (!isNaN(Number(val))) val = Number(val);
frontmatter[key] = val;
}
});
}
// Render common Markdown syntax as HTML
let html = content
.replace(/^### (.*$)/gim, '<h3>$1</h3>')
.replace(/^## (.*$)/gim, '<h2>$1</h2>')
.replace(/^# (.*$)/gim, '<h1>$1</h1>')
.replace(/\*\*(.*?)\*\*/gim, '<strong>$1</strong>')
.replace(/\*(.*?)\*/gim, '<em>$1</em>')
.replace(/`([^`]+)`/gim, '<code>$1</code>')
.replace(/\[([^\]]+)\]\(([^)]+)\)/gim, '<a href="$2">$1</a>')
.replace(/\n\n/gim, '</p><p>')
.trim();
html = `<div class="markdown-body"><p>${html}</p></div>`;
return { frontmatter, html };
};
return {
name: 'vite-plugin-markdown-compiler',
enforce: 'pre',
// 1. Source transform hook
transform(code: string, id: string) {
if (!id.endsWith('.md')) {
return null;
}
const { frontmatter, html } = parseMarkdown(code);
// Generate ES module exports
const compiledModule = `
export const frontmatter = ${JSON.stringify(frontmatter)};
export const html = ${JSON.stringify(html)};
// Export a renderer for vanilla JavaScript
export default function render(container) {
if (typeof container === 'string') {
container = document.querySelector(container);
}
if (container) {
container.innerHTML = html;
}
return { frontmatter, html };
}
// Mark the module as HMR self-accepting
if (import.meta.hot) {
import.meta.hot.accept((newModule) => {
if (newModule) {
window.dispatchEvent(new CustomEvent('markdown-content-updated', {
detail: { id: ${JSON.stringify(id)}, frontmatter: newModule.frontmatter }
}));
}
});
}
`;
return {
code: compiledModule,
map: null, // Add a source map when needed
};
},
// 2. Hot update hook
handleHotUpdate(ctx) {
if (ctx.file.endsWith('.md')) {
console.log(`\x1b[35m[vite-plugin-markdown:hmr]\x1b[0m AST regenerated for ${ctx.file.split('/').pop()}`);
ctx.server.ws.send({
type: 'custom',
event: 'markdown-content-updated',
data: { file: ctx.file },
});
}
},
};
}
I use safely escaped JavaScript literals in the generated source. That is a code-generation concern. If the consumer assigns rendered HTML through innerHTML, untrusted Markdown also needs a sanitizer or a renderer that disallows unsafe HTML. This sample is aimed at source-controlled documents.
TypeScript needs an ambient module declaration for .md. Keep this declaration aligned with the generated exports and make sure the application includes it in its TypeScript project.
1
2
3
4
5
6
7
// src/markdown.d.ts
declare module '*.md' {
export const frontmatter: Record<string, any>;
export const html: string;
const render: (container: HTMLElement | string) => { frontmatter: Record<string, any>; html: string };
export default render;
}
Registering the plugin and rendering a document
Add the compiler to Vite and prepare a document with metadata.
1
2
3
4
5
6
7
8
9
// vite.config.ts
import { defineConfig } from 'vite';
import { markdownCompilerPlugin } from './plugins/vite-plugin-markdown-compiler';
export default defineConfig({
plugins: [
markdownCompilerPlugin(),
],
});
1
2
3
4
5
6
7
8
9
<!-- docs/architecture.md -->
---
title: "Plugin architecture"
author: "Namju Kim"
tags: 5
---
# System architecture
These notes describe how **Vite plugins** fit into the build pipeline.
The client imports the document with the interface defined above.
1
2
3
4
5
// src/main.ts
import renderDoc, { frontmatter } from './docs/architecture.md';
console.log('Document Metadata:', frontmatter);
renderDoc('#app');
For the first manual test, check that the rendered title and headings match the document. Read back the metadata independently of the HTML so a parsing error cannot look like a render-only problem.
Checking development updates and output size
Figure 1. The dev server detects the document change and recompiles the module.
Run npm run dev and edit docs/architecture.md while its consumer is open. The captured example shows roughly 4.2 ms for the Markdown update. Whether the DOM changes without a full reload depends on the accepting module and how the consumer renders the new exports. In a custom renderer, the callback must actually apply the new content. Test that the rest of the client state survives the change you care about.
Figure 2. Inspecting generated document code in the production output.
Run npm run build and look for the generated exports. A dynamic import or manual chunk boundary can place a document in its own chunk. A static import generally gives the bundler more freedom to merge it into an entry or shared chunk. Import specific named exports when you want to make unused data easier to remove.
Extending the output without changing the import contract
Build-time syntax highlighting can emit HTML with Shiki or PrismJS before documents reach the browser. Stable heading slugs and a named toc export give documentation pages their own navigation data. For interactive documents, use a parser and compiler designed for JSX or Vue component integration. Replacing strings cannot provide the consistency or safety of an AST-based pipeline.
- Test front matter and body rendering separately.
- Edit one document with an open consumer and inspect HMR behavior.
- Check that the production chunking matches how the app loads documentation.
- Use a supported parser and validate trust boundaries before allowing user-supplied content.