Reference Compile API

Annotated source

compile turns one document into Svelte component source without Vite. It is synchronous and never touches the filesystem, so it also runs in a browser.

Import it from mdsvex/compile. That entry holds only the compiler, so a bundler never sees the Vite plugin or its lazy imports of Vite and Node builtins. The root mdsvex exports compile too, but its types import vite, so in a project without Vite and with skipLibCheck off, TypeScript reports that it can't find vite.

The result has:

  • code, the Svelte 5 component source;
  • metadata, the parsed frontmatter, or undefined when there is none;
  • template, the name of the template wrapping the document, or undefined;
  • warnings, or undefined when there are none;
  • mappings, from the output back to the document, only with sourcemap: true. mappings_to_v3 from @mdsvex/render/sourcemap makes a v3 source map of them;
  • data, what plugins left in plugin data, by plugin name, or undefined when they left none;
  • snippets, the code of each fence that runs, one per module the output imports, or undefined when none runs;
  • dependencies, the absolute paths of the files the output depends on, or undefined for none. They are what plugins read or named, and, with read and resolve in compile_async, the files fences show and the module of the template.
import { compile } from 'mdsvex/compile';

const { code, metadata } = compile(`---
title: Hello
---

# {metadata.title}
`);
You write
---
title: Hello
---

# {metadata.title}

You get
Compiles to
<script module>
  export const metadata = {
    title: 'Hello',
  };
</script>

<h1>{metadata.title}</h1>

compile resolves nothing. Templates, components and directives are given as the import specifier to write plus the names that module exports. Finding those names is what the Vite plugin does for you.

compile(source, {
	templates: {
		default: { specifier: '/src/Post.svelte', components: ['h2', 'p'] }
	},
	components: [{ specifier: '/src/markdown.js', names: ['img'] }],
	directives: [{ specifier: '/src/directives.js', names: ['Callout'] }]
});

The output imports from those specifiers exactly as written.

compile doesn't highlight code unless you pass highlight, see highlighting with compile.

  • A directive with no component is an error. For a preview or an editor, pass strict_directives: false to render it as its children instead.

default_template names the template of a document whose frontmatter and select_template pick none, in place of the default entry:

compile(source, {
	templates: { post: { specifier: '/src/Post.svelte', components: [] } },
	default_template: 'post'
});

select_template takes the same arguments as the Vite plugin's, select_template(filename, metadata), with filename undefined for a compile without one, see select_template with compile.

On the atlas: template.

A plugin that waits for something, a file or an endpoint, defers that work, and compile throws a PluginAsyncError when one does. compile_async takes the same options, waits for that work, and gives the same result once it applied:

import { readFile } from 'node:fs/promises';
import { compile_async } from 'mdsvex/compile';
import { citations } from '@mdsvex/plugin-citations';

// the frontmatter of /site/post.svx names ./refs.json, so the plugin reads /site/refs.json
const { code, data } = await compile_async(source, {
	filename: '/site/post.svx',
	read: (file) => readFile(file, 'utf8'),
	plugins: [citations()]
});

A document whose plugins defer nothing compiles exactly as it does with compile.

A plugin that loads a file finds a relative path from filename and loads it with read, see read and resolve. Without filename the citations plugin can't find ./refs.json, and without read it can't load it, and either fails the compile.

  • A task that fails rejects with a PluginTaskError that names the plugin and the line of the node, with the task's error as its cause.

Given read and resolve options, compile_async reads the files fences show with src= itself, resolved from filename, so a host that is not Vite needs no sources. The result's dependencies then name those files and the module of the template, beside what plugins read, for the host to watch:

const { code, dependencies } = await compile_async(source, {
	filename: '/site/post.svx',
	read: (path) => fs.readFile(path, 'utf8'),
	resolve: (specifier, from) => path.resolve(path.dirname(from), specifier)
});

What plugins load with ctx.cached is kept between calls for as long as you pass the same plugins array, which suits a build that runs once. A host that compiles again when files change passes a CompilerSession of its own as the third argument, and calls its invalidate with the paths that changed before compiling the documents whose dependencies list them:

import { CompilerSession, compile_async } from 'mdsvex/compile';

const session = new CompilerSession();
const { code, dependencies } = await compile_async(source, options, session);

// later, when a watched file changes
session.invalidate([changed]);
await compile_async(source, options, session);

Back to page index

mdsvex, markdown with Svelte in it. MIT licence.