0.5.0 • Published 4 months ago

@temelj/mdx v0.5.0

Weekly downloads
-
License
MIT
Repository
github
Last release
4 months ago

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.