satyarohith / sift

Sift is a routing and utility library for Deno Deploy.

Home Page:https://deno.land/x/sift

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Utility function for markdown.

hastebrot opened this issue · comments

Similar to jsx() there could be a function mdx() which transforms a markdown or mdx string into html.

Simple example how to transform markdown to html.

// deno run --no-check markdown.ts

import { VFile, type VFileCompatible } from "https://esm.sh/vfile@5.3.2";
import type { Plugin } from "https://esm.sh/unified@10.1.2";
import type { Node as UnistNode } from "https://esm.sh/@types/unist@2.0.6";
import type { Root as MdastRoot } from "https://esm.sh/@types/mdast@3.0.10";
import type { Root as HastRoot } from "https://esm.sh/@types/hast@2.3.4";

// md processor.
import { unified } from "https://esm.sh/unified@10.1.2";
import rehypeSanitize from "https://esm.sh/rehype-sanitize@5.0.1";
import rehypeStringify from "https://esm.sh/rehype-stringify@9.0.3";
import remarkFrontmatter from "https://esm.sh/remark-frontmatter@4.0.1";
import remarkGfm from "https://esm.sh/remark-gfm@3.0.1";
import remarkParse from "https://esm.sh/remark-parse@10.0.1";
import remarkRehype from "https://esm.sh/remark-rehype@10.1.0";

// mdx compiler.
import { compile } from "https://esm.sh/@mdx-js/mdx@2.1.0";
import { remarkMdxFrontmatter } from "https://esm.sh/remark-mdx-frontmatter@1.1.1";

if (import.meta.main) {
  const printFile = (file: VFile) => {
    console.log("file:", file);
    return file;
  };
  const printNode = <T extends UnistNode | MdastRoot | HastRoot>(node: T) => {
    console.log("node:", node);
    return node;
  };

  const processor = unified()
    .use(remarkParse)
    .use(remarkFrontmatter)
    .use(() => printNode)
    .use(remarkGfm)
    .use(remarkRehype)
    .use(rehypeSanitize)
    .use(rehypeStringify)
    .freeze();

  printFile(
    await processor.process(
      new VFile({
        path: "~/example.md",
        value: "Alpha **bravo** charlie.",
      }),
    ),
  );

  const compiler = {
    compile(doc: VFileCompatible): Promise<VFile> {
      return compile(doc, {
        format: "mdx",
        outputFormat: "program",
        jsx: true,
        jsxRuntime: "classic",
        pragma: "React.createElement",
        pragmaFrag: "React.Fragment",
        rehypePlugins: [],
        remarkPlugins: [
          remarkFrontmatter,
          [remarkMdxFrontmatter as Plugin, { name: "attributes" }],
          () => printNode,
        ],
      });
    },
  };

  printFile(
    await compiler.compile(
      new VFile({
        path: "~/example.mdx",
        value: "Alpha **bravo** charlie.",
      }),
    ),
  );
}

There is quite an ecosystem behind the mdx compiler suite: