Skip to content

mdast extension to parse and serialize MDX (or MDX.js)

License

Notifications You must be signed in to change notification settings

syntax-tree/mdast-util-mdx

Repository files navigation

mdast-util-mdx

Build Coverage Downloads Size Sponsors Backers Chat

mdast extensions to parse and serialize MDX: ESM import/exports, JavaScript expressions, and JSX.

Contents

What is this?

This package contains extensions for mdast-util-from-markdown and mdast-util-to-markdown to enable the features that MDX adds to markdown: import/exports (export x from 'y'), expressions ({z}), and JSX (<Component />).

When to use this

These tools are all rather low-level. In many cases, you’d want to use remark-mdx with remark instead.

Use this if you’re dealing with the AST manually and want to support all of MDX. Instead of this package, you can also use the extensions separately:

When working with mdast-util-from-markdown, you must combine this package with micromark/micromark-extension-mdx or micromark/micromark-extension-mdxjs.

Install

This package is ESM only. In Node.js (version 12.20+, 14.14+, or 16.0+), install with npm:

npm install mdast-util-mdx

In Deno with esm.sh:

import {mdxFromMarkdown, mdxToMarkdown} from 'https://esm.sh/mdast-util-mdx@2'

In browsers with esm.sh:

<script type="module">
  import {mdxFromMarkdown, mdxToMarkdown} from 'https://esm.sh/mdast-util-mdx@2?bundle'
</script>

Use

Say our document example.mdx contains:

import Box from "place"

Here’s an expression:

{
  1 + 1 /* } */
}

Which you can also put inline: {1+1}.

<Box>
  <SmallerBox>
    - Lists, which can be indented.
  </SmallerBox>
</Box>

…and our module example.js looks as follows:

import fs from 'node:fs/promises'
import {fromMarkdown} from 'mdast-util-from-markdown'
import {toMarkdown} from 'mdast-util-to-markdown'
import {mdxjs} from 'micromark-extension-mdxjs'
import {mdxFromMarkdown, mdxToMarkdown} from 'mdast-util-mdx'

const doc = await fs.readFile('example.mdx')

const tree = fromMarkdown(doc, {
  extensions: [mdxjs()],
  mdastExtensions: [mdxFromMarkdown()]
})

console.log(tree)

const out = toMarkdown(tree, {extensions: [mdxToMarkdown()]})

console.log(out)

…now running node example.js yields (positional info removed for brevity):

{
  type: 'root',
  children: [
    {
      type: 'mdxjsEsm',
      value: 'import Box from "place"',
      data: {
        estree: {
          type: 'Program',
          body: [
            {
              type: 'ImportDeclaration',
              specifiers: [
                {
                  type: 'ImportDefaultSpecifier',
                  local: {type: 'Identifier', name: 'Box'}
                }
              ],
              source: {type: 'Literal', value: 'place', raw: '"place"'}
            }
          ],
          sourceType: 'module'
        }
      }
    },
    {
      type: 'paragraph',
      children: [{type: 'text', value: 'Here’s an expression:'}]
    },
    {
      type: 'mdxFlowExpression',
      value: '\n1 + 1 /* } */\n',
      data: {
        estree: {
          type: 'Program',
          body: [
            {
              type: 'ExpressionStatement',
              expression: {
                type: 'BinaryExpression',
                left: {type: 'Literal', value: 1, raw: '1'},
                operator: '+',
                right: {type: 'Literal', value: 1, raw: '1'}
              }
            }
          ],
          sourceType: 'module'
        }
      }
    },
    {
      type: 'paragraph',
      children: [
        {type: 'text', value: 'Which you can also put inline: '},
        {
          type: 'mdxTextExpression',
          value: '1+1',
          data: {
            estree: {
              type: 'Program',
              body: [
                {
                  type: 'ExpressionStatement',
                  expression: {
                    type: 'BinaryExpression',
                    left: {type: 'Literal', value: 1, raw: '1'},
                    operator: '+',
                    right: {type: 'Literal', value: 1, raw: '1'}
                  }
                }
              ],
              sourceType: 'module'
            }
          }
        },
        {type: 'text', value: '.'}
      ]
    },
    {
      type: 'mdxJsxFlowElement',
      name: 'Box',
      attributes: [],
      children: [
        {
          type: 'mdxJsxFlowElement',
          name: 'SmallerBox',
          attributes: [],
          children: [
            {
              type: 'list',
              ordered: false,
              start: null,
              spread: false,
              children: [
                {
                  type: 'listItem',
                  spread: false,
                  checked: null,
                  children: [
                    {
                      type: 'paragraph',
                      children: [
                        {type: 'text', value: 'Lists, which can be indented.'}
                      ]
                    }
                  ]
                }
              ]
            }
          ]
        }
      ]
    }
  ]
}
import Box from "place"

Here’s an expression:

{
  1 + 1 /* } */
}

Which you can also put inline: {1+1}.

<Box>
  <SmallerBox>
    *   Lists, which can be indented.
  </SmallerBox>
</Box>

API

This package exports the identifiers mdxFromMarkdown and mdxToMarkdown. There is no default export.

mdxFromMarkdown()

Extension for mdast-util-from-markdown.

When using the syntax extension with addResult, nodes will have a data.estree field set to an ESTree.

mdxToMarkdown(options?)

Extension for mdast-util-to-markdown.

options

Configuration (optional). Currently passes through quote, quoteSmart, tightSelfClosing, and printWidth to mdast-util-mdx-jsx.

Syntax tree

This utility combines several mdast utilities. See their readmes for the node types supported in the tree:

Types

This package is fully typed with TypeScript. It exports the additional types MdxFlowExpression, MdxTextExpression, MdxjsEsm, MdxJsxAttributeValueExpression, MdxJsxAttribute, MdxJsxExpressionAttribute, MdxJsxFlowElement, MdxJsxTextElement, and ToMarkdownOptions.

It also registers the node types with @types/mdast. If you’re working with the syntax tree, make sure to import this utility somewhere in your types, as that registers the new node types in the tree.

/**
 * @typedef {import('mdast-util-mdx')}
 */

import {visit} from 'unist-util-visit'

/** @type {import('mdast').Root} */
const tree = getMdastNodeSomeHow()

visit(tree, (node) => {
  // `node` can now be an expression, JSX, or ESM node.
})

Compatibility

Projects maintained by the unified collective are compatible with all maintained versions of Node.js. As of now, that is Node.js 12.20+, 14.14+, and 16.0+. Our projects sometimes work with older versions, but this is not guaranteed.

This utility works with mdast-util-from-markdown version 1+ and mdast-util-to-markdown version 1+.

Related

Contribute

See contributing.md in syntax-tree/.github for ways to get started. See support.md for ways to get help.

This project has a code of conduct. By interacting with this repository, organization, or community you agree to abide by its terms.

License

MIT © Titus Wormer