Syntax Highlighting
Add beautiful syntax highlighting to your markdown code blocks with MDSX.
MDSX doesn't include syntax highlighting out of the box, but provides @mdsx/rehype-custom-highlighter
that gives you complete control over how code is highlighted.
Quick Start
Install the Plugin
npm install -D @mdsx/rehype-custom-highlighter
The plugin is lightweight and provides the foundation for any syntax highlighter.
Configure Your Highlighter
import { defineConfig } from 'mdsx';
import { rehypeCustomHighlighter } from '@mdsx/rehype-custom-highlighter';
/** @type {import('@mdsx/rehype-custom-highlighter').HighlightOptions} */
const highlightOptions = {
highlight: async ({ value, lang, meta }) => {
// your highlighting logic here
return value;
},
};
export const mdsxConfig = defineConfig({
extensions: ['.md'],
rehypePlugins: [[rehypeCustomHighlighter, highlightOptions]],
});
This sets up the basic structure - you'll replace the highlight function with your preferred highlighter.
Write Your Markdown
# My Documentation
Here's some JavaScript code:
```js
function greet(name) {
return `Hello, ${name}!`;
}
```
And some CSS:
```css
.button {
background: blue;
color: white;
padding: 10px;
}
```
Your code blocks will now be processed by your chosen highlighter.
Plugin Configuration
The @mdsx/rehype-custom-highlighter
plugin accepts a single configuration option:
type HighlightOptions = {
highlight?: (args: HighlightCallbackArgs) => MaybePromise<string | undefined>;
};
Highlight Function Parameters
Your highlight function receives an object with these properties:
type HighlightCallbackArgs = {
lang: string | null | undefined; // language from code block
value: string | undefined; // code content
meta: string | null | undefined; // metastring (title, line numbers, etc.)
};
Example: Understanding the Parameters
Consider this markdown code block:
```js title="example.js" showLineNumbers
console.log('hello world');
```
The highlight function would receive:
lang
:"js"
- the language identifiervalue
:"console.log('hello world');"
- the actual codemeta
:"title="example.js" showLineNumbers"
- the metastring
Return Value
Your highlight function should return a string containing the HTML for the highlighted code. This HTML will be inserted directly into the final output.
Next Steps
Check out the Shiki recipe for a complete example of how to setup Shiki with MDSX.