Recipes

Custom Highlighter

Learn how to add syntax highlighting to your markdown files.

Syntax highlighting doesn't come out of the box with MDSX. There are a number of different syntax highlighters out there, and this project aims to be as unopinionated as possible.

With that said, we do maintain an official plugin that enables you to use whichever syntax highlighter you desire - @mdsx/rehype-custom-highlighter.

Using a Custom Highlighter

Before diving into our Syntax Highlighting guide, let's cover how to use this plugin. It's super simple.

Installation

First, install the plugin.

	npm install -D @mdsx/rehype-custom-highlighter	

Configuration

Next, you'll need to setup the configuration options for the plugin, which you can do in your mdsx.config.js file.

mdsx.config.js
	/** @type {import('@mdsx/rehype-custom-highlighter').HighlightOptions} */
const customHighlightOptions = {
	highlight: async ({ value, lang, meta }) => {
		// Do something with the value, lang, and meta
		return value;
	},
};	

HighlightOptions has a single property, highlight, which is a function with a parameter of the following type:

	type HighlightCallbackArgs = {
	lang: string | null | undefined;
	value: string | undefined;
	meta: string | null | undefined;
};	

lang is the language pulled from the fenced code block, value is the code within the fenced code block, and meta is the metastring associated with the fenced code block.

For example, consider the following code block:

	```js title="example.md" showLineNumbers
console.log('hello world');
```	

In the above example:

  • lang would evaluate to "js".

  • value would evaluate to "console.log('hello world');".

  • meta would evaluate to "title="example.md" showLineNumbers".

A string should be returned from the highlight function, which will be used as the HTML for the highlighted code block. Within this function you can use any syntax highlighter you want, or even write your own. The sky's the limit! 🚀

Applying the Plugin

Now that you have your highlighter configured, you just need to apply it to your MDSXConfig, either at the top-level or blueprint level.

mdsx.config.js
	import { defineConfig } from 'mdsx';
import { rehypeCustomHighlighter } from '@mdsx/rehype-custom-highlighter';
 
// ... customHighlightOptions
 
export const mdsxConfig = defineConfig({
	extensions: ['.md'],
	rehypePlugins: [[rehypeCustomHighlighter, customHighlightOptions]],
});	

And that's it! You're now using your own custom syntax highlighter with MDSX.

Be sure to check out the Syntax Highlighting guide for examples of how to use some of the more popular syntax highlighters.

MIT

© 2025 Svecosystem Team