Skip to content

Files

Latest commit

Apr 29, 2025
a54cbdb · Apr 29, 2025

History

History

mdx

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
Apr 29, 2025
Feb 19, 2025
Apr 29, 2025
Apr 29, 2025
Apr 29, 2025
Nov 27, 2024
Apr 29, 2025
Apr 29, 2025

@temelj/mdx


Utilities for working with MDX.

Created by Tin Rabzelj jsr License

jsr   •   npm   •   Issues   •   @tinrab


Installation

# npm
$ npm install @temelj/mdx
# jsr
$ deno add jsr:@temelj/mdx # or jsr add @temelj/mdx

Compile

import { assert, assertEquals } from "@std/assert";
import {
  type HastElement,
  headingIdPlugin,
  MdxCompiler,
  syntaxHighlightPlugin,
  treeProcessorPlugin,
} from "@temelj/mdx";
import { z } from "zod";

const compiler = new MdxCompiler()
  .withRehypePlugin(headingIdPlugin, {
    prefix: "h-",
  })
  .withRehypePlugin(syntaxHighlightPlugin, {
    highlight: {},
    lineNumbers: {},
    commandLine: {},
    shikiHastOptions: {
      // themes: {
      //   light: lightTheme,
      //   dark: darkTheme,
      // },
    },
  });

const source = `
---
title: Demo
---
# Hello

This will compile MDX to a render-able artifact.
With '@temelj/mdx-react' you can render it in an React app.

You can validate the frontmatter with a zod schema.

There are a few useful plugins:
- Use 'headingIdPlugin' to update heading tags (h1, h2, etc.) with IDs generated by slugging their text content.
This is useful for linking to headings in a page.
- Use 'syntaxHighlightPlugin' to highlight code blocks using [Shiki](https://github.com/shikijs/shiki).
You can highlight individual lines, show line numbers, or display a prompt.
- Use 'treeProcessorPlugin' to modify the HAST tree.
For example, change image URLs to point to a CDN.

\`\`\`bash {"commandLine": "0"}
whoamai
@temelj/mdx
\`\`\`
`.trim();
const artifact = await compiler.compile(
  source,
  {
    frontmatterOnly: false,
    mdxOptions: {
      rehypePlugins: [
        [
          treeProcessorPlugin,
          {
            process: (node: HastElement) =>
              assert(typeof node.type === "string"),
          },
        ],
      ],
    },
  },
  z.object({
    title: z.string(),
  }),
);
assert(artifact.compiled !== undefined);
assertEquals(artifact.frontmatter, {
  title: "Demo",
});

About

This package is part of Temelj - a big standard library for TypeScript.