MDX Export Definition Utility

1.1.2 · active · verified Sun Apr 19

unist-util-mdx-define is a utility for the Unist ecosystem designed to simplify the process of defining exports within an MDX Abstract Syntax Tree (AST). It abstracts away the complexities of AST manipulation, allowing developers to easily expose variables from remark (mdast), rehype (hast), or recma (estree/esast) plugins. As of the current stable version 1.1.2, the package maintains a steady release cadence for minor and patch updates, focusing on robustness and compatibility within the `unified` and `MDX.js` ecosystems. Its key differentiator is its ability to uniformly inject export declarations across different stages of the MDX compilation pipeline (mdast, hast, estree), ensuring that variables defined at any stage are correctly available in the final MDX module without requiring manual AST traversal or complex insertion logic.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to use `unist-util-mdx-define` within `remark`, `rehype`, and `recma` MDX plugins to export variables, which are then accessible in the MDX content.

import { compile } from '@mdx-js/mdx'
import type * as estree from 'estree'
import type * as hast from 'hast'
import type * as mdast from 'mdast'
import { type Plugin } from 'unified'
import { define } from 'unist-util-mdx-define'

const yourRemarkMdxPlugin: Plugin<[], mdast.Root> = () => (ast, file) => {
  define(ast, file, { remarkVariable: { type: 'Literal', value: 'Hello remark plugin!' } })
}

const yourRehypeMdxPlugin: Plugin<[], hast.Root> = () => (ast, file) => {
  define(ast, file, { rehypeVariable: { type: 'Literal', value: 'Hello rehype plugin!' } })
}

const yourRecmaMdxPlugin: Plugin<[], estree.Program> = () => (ast, file) => {
  define(ast, file, { recmaVariable: { type: 'Literal', value: 'Hello recma plugin!' } })
}

async function runExample() {
  const { value } = await compile('{remarkVariable} {rehypeVariable} {recmaVariable}', {
    remarkPlugins: [yourRemarkMdxPlugin],
    rehypePlugins: [yourRehypeMdxPlugin],
    recmaPlugins: [yourRecmaMdxPlugin]
  })
  console.log(value)
}

runExample()

view raw JSON →