Guides Coming from remark and rehype

Source

mdsvex 0.x ran remark and rehype, and took their plugins in remarkPlugins and rehypePlugins. mdsvex now has its own parser, so those plugins don't run and the two options are gone. Most of what they were used for is built in, an option, or a first-party plugin. Find each plugin you used below, and for one you wrote yourself, see porting a plugin of your own.

migrate_config from the migrator leaves a note for every plugin it finds in your config, with the same answer.

remark-gfm, remark-footnotes

built in, apart from one thing: tables, ~~strikethrough~~, task lists and footnotes work as written. A bare url is not linked: the migrator writes each one as <https://example.com>, and references({ linkify: true }) from @mdsvex/plugin-references links them all

remark-frontmatter, remark-parse-yaml

built in: frontmatter is the metadata export, and frontmatter.parse takes TOML or full YAML

remark-directive, remark-admonitions, remark-containers, remark-custom-blocks

built in: directives, :::note renders your note component

remark-sub-super, remark-supersub

built in: H~2~O and x^2^

remark-extended-table, rehype-merge-cells

built in: a > or ^ cell merges, and || makes header columns

remark-math with rehype-katex, rehype-katex-svelte or rehype-mathjax

built in: a math fence and $`x`$, rendered by Temml or, with math: { renderer: 'katex' }, KaTeX. For MathJax pass a function. The migrator rewrites $x$ when you pass math: true

remark-code-import

built in: src=./file.ts#L5-L20 on a fence, the migrator renames file=

remark-breaks

nothing, on purpose: a line end is a space. End a line with a backslash for a break

rehype-raw

not needed: HTML in a document is always real markup

remark-smartypants, and the smartypants option

an option: smart_punctuation: true, off by default

rehype-slug, remark-slug

an option: heading_ids: true, which the migrator adds

remark-unwrap-images, rehype-unwrap-images

an option: unwrap_images: true, which the migrator adds

mdsvex-relative-images, remark-embed-images

on by default: a relative image is imported, so Vite hashes it

rehype-highlight, remark-highlight.js, rehype-prism-plus, remark-prism, @shikijs/rehype, rehype-pretty-code

on by default: highlighting needs a theme and no setup. Fence meta reads {1,3-4}, /word/ and showLineNumbers as they do. For Shiki itself pass a function

rehype-code-titles, remark-code-titles, remark-flexible-code-titles

built in: title="math.ts" or [math.ts] in the fence meta

rehype-twoslash

remark-toc, rehype-toc, @stefanprobst/rehype-extract-toc, @vcarl/remark-headings

@mdsvex/plugin-toc: toc() leaves the headings as data, and ::toc lists them in the page

remark-reading-time

@mdsvex/plugin-page-data: plugin_data.page.minutes and words

rehype-infer-description-meta, rehype-infer-title-meta, rehype-truncate

@mdsvex/plugin-page-data: plugin_data.page.excerpt and title, as text

rehype-code-group

@mdsvex/plugin-tabs: :::tabs around the fences

remark-emoji, remark-gemoji

@mdsvex/plugin-emoji: emoji() turns :tada: into the emoji, with GitHub's names

remark-github, remark-mentions, remark-ping

@mdsvex/plugin-references: references({ repo: 'you/site' }) links @user, #123 and commits

rehype-citation

@mdsvex/plugin-citations: :cite[key] from a CSL JSON file, and ::bibliography

remark-github-blockquote-alert, remark-github-alerts, rehype-callouts, remark-obsidian-callout, remark-github-admonitions-to-directives, remark-github-beta-blockquote-admonitions

@mdsvex/plugin-callouts: :::note, :::tip, :::important, :::warning and :::caution. The migrator rewrites > [!NOTE] as :::note, and leaves a note at Obsidian's other kinds and at a callout that folds

rehype-rewrite, rehype-wrap, rehype-components

a component: replace the element with a component of your own

rehype-class-names, rehype-add-classes

a parse plugin: { table: { parse(node) { node.attrs.class = 'table'; } } } in parse_plugins

remark-sectionize, rehype-section

a parse plugin: the sections plugin under plugin handlers

rehype-figure, remark-figure-caption

@mdsvex/plugin-figures: :::figure[Caption] around an image or anything else, with the caption in a <figcaption>. A lone image stays an image

rehype-img-size, rehype-plugin-image-native-lazy-loading

@sveltejs/enhanced-img and a component: add enhancedImages() to your Vite plugins and every markdown image gets its width and height, with avif and webp sources, see optimised images. For loading="lazy", an img replacement sets it, and gets the picture as src

rehype-mermaid, remark-mermaidjs

@mdsvex/plugin-diagram: diagram() draws each mermaid fence, at build time with pele installed or in the browser with mermaid

remark-embedder, remark-oembed, remark-youtube

@mdsvex/plugin-embeds: ::youtube[A talk](id=dQw4w9WgXcQ) and ::vimeo. Any other site is a leaf directive with a component of your own, see directives

remark-collapse

nothing needed: <details> and <summary> work as typed, with markdown inside, and @mdsvex/plugin-elements adds :::details[Summary] and accordions

remark-kbd, remark-ruby

@mdsvex/plugin-elements: :kbd[Ctrl] and :ruby[漢字](rt=かんじ)

remark-flexible-markers, remark-mark-highlight, remark-ins

@mdsvex/plugin-elements: :mark[text] and :ins[text]. ==mark== and ++ins++ are text, a plugin can't add syntax

remark-abbr

@mdsvex/plugin-elements: :abbr[HTML](title="HyperText Markup Language")

rehype-meta, rehype-document

a template: a template renders <svelte:head> from its props

rehype-video

a component: an a or img replacement that renders a <video> for a video url

remark-heading-id, remark-attr, rehype-attr

{#id} and {.class} can't exist, braces belong to Svelte. heading_ids makes ids, and a parse plugin can set any attribute

remark-definition-list, remark-deflist

type <dl>, <dt> and <dd>

remark-lint

nothing checks style. @mdsvex/plugin-link-check checks links, and a missing image fails the build when it is imported

rehype-sanitize

nothing, and none is planned. A document compiles to a component and runs as code, so don't compile markdown you don't trust

rehype-minify, rehype-format

not needed, Svelte and Vite own the output

A plugin that is not listed did one of three things. If it changed elements or attributes, a parse plugin can do the same. If it added syntax, a directive is the syntax mdsvex has for that, and plugins can't add more. If it needed to fetch something or read a file while compiling, a plugin does that in deferred work.

Each plate below is a remark pattern, then the same plugin for mdsvex. An mdsvex plugin is an object with a name and its handlers under parse, passed to mdsvex({ plugins: [...] }).

A remark plugin walks the finished tree with visit. An mdsvex plugin names the node type instead, and its handler runs for each node of that type while the parser reads the document. A link has its url and its text once it closes, so the handler returns a function that runs then:

// remark
import { visit } from 'unist-util-visit';
import { toString } from 'mdast-util-to-string';

export function vague_links() {
	return (tree, file) => {
		visit(tree, 'link', (node) => {
			if (toString(node).trim().toLowerCase() === 'click here')
				file.message('say where the link goes, not "click here"', node);
		});
	};
}
// mdsvex
export function vague_links() {
	return {
		name: 'vague_links',
		parse: {
			link: {
				parse(node, ctx) {
					return () => {
						if (node.text_content.trim().toLowerCase() === 'click here')
							ctx.warn('vague_link', 'say where the link goes, not "click here"', node);
					};
				}
			}
		}
	};
}

toString(node) is node.text_content, node.url is node.href, and file.message is ctx.warn, which the build prints with the line of the node. A plugin that handles several types has a key for each.

  • A handler sees the document up to its node, not past it. A visit that reads ahead becomes a plugin with sequential: true, which runs over the finished tree, or a document hook.

Most mdast types keep their name. These are written differently:

remarkmdsvex
strongstrong_emphasis
deletestrikethrough
inlineCodecode_span
codecode_fence
blockquoteblock_quote
listItemlist_item
tableRow, tableCelltable_row, table_cell, and table_header for the header row
thematicBreakthematic_break
breakhard_break
yamlfrontmatter
textDirective, leafDirective, containerDirectivedirective_inline, directive_leaf, directive_container
htmlhtml for each element or component, html_comment for a comment

A rehype plugin that matched an element by its tagName keys by what the markdown wrote instead: a is link, img is image, and h1 to h6 are heading, with a depth. Plugin handlers lists every type.

remark sets an attribute through data.hProperties, and rehype through properties. An mdsvex handler writes it to node.attrs:

// remark
import { visit } from 'unist-util-visit';

export function table_class() {
	return (tree) => {
		visit(tree, 'table', (node) => {
			node.data = { ...node.data, hProperties: { className: ['table'] } };
		});
	};
}
// mdsvex
const table_class = {
	name: 'table_class',
	parse: {
		table: {
			parse(node) {
				node.attrs.class = 'table';
			}
		}
	}
};

mdsvex({ plugins: [table_class] });
You write
| Plugin | Port |
| --- | --- |
| remark | `attrs` |
You get
Compiles to
<table class="table">
  <thead>
    <tr>
      <th>Plugin</th>
      <th>Port</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>remark</td>
      <td><code>attrs</code></td>
    </tr>
  </tbody>
</table>

attrs takes HTML names, so class where rehype has className, as one string. On an element that a replacement renders, an attribute becomes a prop.

  • An element written as HTML keeps what was written on it in attrs.attributes. Set a new object there, in the function the handler returns: node.attrs.attributes = { ...node.attrs.attributes, class: 'wide' }.

In mdsvex 0.x a remark plugin added keys to the frontmatter through file.data.fm, and the page read them in metadata. A plugin now writes with ctx.set or ctx.add, and the page reads it in plugin_data, under the plugin's name:

// remark, for mdsvex 0.x
import { toString } from 'mdast-util-to-string';

export function reading_time() {
	return (tree, file) => {
		const words = toString(tree).split(/\s+/).length;
		file.data.fm.minutes = Math.ceil(words / 200);
	};
}
// mdsvex
const reading_time = {
	name: 'reading_time',
	parse: {
		document(root, ctx) {
			const words = root.text_content.split(/\s+/).length;
			ctx.set('minutes', Math.ceil(words / 200));
		}
	}
};

mdsvex({ plugins: [reading_time] });
You write
---
title: A short post
---

It takes {plugin_data.reading_time.minutes} minute to read.
You get
Compiles to
<script module>
  export const metadata = {
    title: 'A short post',
  };
  export const plugin_data = {
    reading_time: { minutes: 1 },
  };
</script>

<script>
  import { setContext as set_context_MDSVEX } from 'svelte';
  set_context_MDSVEX(
    Symbol.for('mdsvex.plugin_data'),
    { current: plugin_data },
  );
</script>

<p>
  It takes {plugin_data.reading_time
    .minutes} minute to read.
</p>
  • Plugins can't write metadata. It is the frontmatter the author wrote and nothing else, and ctx.frontmatter reads it but must not change it. So no plugin can overwrite a key that the author or another plugin wrote, since each plugin writes under its own name. And a page or a template can tell where a value came from: metadata.title was written, plugin_data.reading_time.minutes was worked out.
  • A template gets both as props, and a ?data import gives both to a list of posts.
  • A value worked out from the frontmatter or the path alone belongs in metadata, through frontmatter.parse.

A remark transformer could be async and await anything. An mdsvex handler is synchronous: it starts the work with ctx.defer(node, task), and the task changes the node when it finishes:

// remark
import { visit } from 'unist-util-visit';

export function link_titles() {
	return async (tree) => {
		const links = [];
		visit(tree, 'link', (node) => links.push(node));
		await Promise.all(
			links.map(async (node) => {
				const page = await fetch(node.url).then((r) => r.text());
				node.title = page.match(/<title>(.*?)<\/title>/)?.[1];
			})
		);
	};
}
// mdsvex
export function link_titles() {
	return {
		name: 'link_titles',
		parse: {
			link: {
				parse(node, ctx) {
					return () =>
						ctx.defer(node, async (node) => {
							const page = await fetch(node.href).then((r) => r.text());
							node.attrs.title = page.match(/<title>(.*?)<\/title>/)?.[1];
						});
				}
			}
		}
	};
}
  • No list to collect. Each link starts its own task, and the Vite plugin waits for all of them before it renders the document. With compile, use compile_async.
  • Read files with ctx.read, not fs.readFile. It reads through the Vite plugin and makes the file a dependency, so an edit to it compiles the document again. See loading files.
  • A task changes its own node and what is inside it. Anything else throws a TypeError, where a remark transformer could change the whole tree. Work that needs the whole tree goes in a document hook, which may be async.

A remark plugin that worked a value out of the frontmatter or the path of the file, and wrote it to file.data.fm, becomes a frontmatter.parse. It gets the text of the frontmatter and { filename }, and what it returns is metadata:

// remark, for mdsvex 0.x
export function dated_posts() {
	return (tree, file) => {
		const [, date, slug] = file.filename.match(/(\d{4}-\d{2}-\d{2})-([^/]+)\.svx$/) ?? [];
		Object.assign(file.data.fm, { date, slug });
	};
}
// mdsvex
import { parse } from 'yaml';

mdsvex({
	frontmatter: {
		parse: (raw, { filename }) => {
			const [, date, slug] = filename?.match(/(\d{4}-\d{2}-\d{2})-([^/]+)\.svx$/) ?? [];
			return { date, slug, ...parse(raw) };
		}
	}
});
You write src/posts/2026-11-15-hello-world.svx
---
title: Hello world
---
You get
Compiles to
<script module>
  export const metadata = {
    date: '2026-11-15',
    slug: 'hello-world',
    title: 'Hello world',
  };
</script>
  • It runs wherever the frontmatter is read: the compiled document, a ?metadata import and ctx.frontmatter. A list of posts sees the same date as the page.
  • It replaces the built-in parser, so it parses the YAML itself, here with yaml. See custom frontmatter parsers.
  • filename is undefined for a document compiled without a path, as compile() is without its filename option.
  • It sees only the frontmatter. A value worked out from the body, such as a reading time, is plugin data.

Back to page index

mdsvex, markdown with Svelte in it. MIT licence.