site/node_modules/mdast-util-mdx-jsx/readme.md
2024-10-14 08:09:33 +02:00

19 KiB
Raw Blame History

mdast-util-mdx-jsx

Build Coverage Downloads Size Sponsors Backers Chat

mdast extensions to parse and serialize MDX JSX (<a />).

Contents

What is this?

This package contains two extensions that add support for MDX JSX syntax in markdown to mdast. These extensions plug into mdast-util-from-markdown (to support parsing JSX in markdown into a syntax tree) and mdast-util-to-markdown (to support serializing JSX in syntax trees to markdown).

JSX is an XML-like syntax extension to ECMAScript (JavaScript), which MDX brings to markdown. For more info on MDX, see What is MDX?

When to use this

You can use these extensions when you are working with mdast-util-from-markdown and mdast-util-to-markdown already.

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

When you are working with syntax trees and want all of MDX, use mdast-util-mdx instead.

All these packages are used in remark-mdx, which focusses on making it easier to transform content by abstracting these internals away.

Install

This package is ESM only. In Node.js (version 16+), install with npm:

npm install mdast-util-mdx-jsx

In Deno with esm.sh:

import {mdxJsxFromMarkdown, mdxJsxToMarkdown} from 'https://esm.sh/mdast-util-mdx-jsx@3'

In browsers with esm.sh:

<script type="module">
  import {mdxJsxFromMarkdown, mdxJsxToMarkdown} from 'https://esm.sh/mdast-util-mdx-jsx@3?bundle'
</script>

Use

Say our document example.mdx contains:

<Box>
  - a list
</Box>

<MyComponent {...props} />

<abbr title="Hypertext Markup Language">HTML</abbr> is a lovely language.

…and our module example.js looks as follows:

import fs from 'node:fs/promises'
import * as acorn from 'acorn'
import {mdxJsx} from 'micromark-extension-mdx-jsx'
import {fromMarkdown} from 'mdast-util-from-markdown'
import {mdxJsxFromMarkdown, mdxJsxToMarkdown} from 'mdast-util-mdx-jsx'
import {toMarkdown} from 'mdast-util-to-markdown'

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

const tree = fromMarkdown(doc, {
  extensions: [mdxJsx({acorn, addResult: true})],
  mdastExtensions: [mdxJsxFromMarkdown()]
})

console.log(tree)

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

console.log(out)

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

{
  type: 'root',
  children: [
    {
      type: 'mdxJsxFlowElement',
      name: 'Box',
      attributes: [],
      children: [
        {
          type: 'list',
          ordered: false,
          start: null,
          spread: false,
          children: [
            {
              type: 'listItem',
              spread: false,
              checked: null,
              children: [
                {type: 'paragraph', children: [{type: 'text', value: 'a list'}]}
              ]
            }
          ]
        }
      ]
    },
    {
      type: 'mdxJsxFlowElement',
      name: 'MyComponent',
      attributes: [
        {
          type: 'mdxJsxExpressionAttribute',
          value: '...props',
          data: {
            estree: {
              type: 'Program',
              body: [
                {
                  type: 'ExpressionStatement',
                  expression: {
                    type: 'ObjectExpression',
                    properties: [
                      {
                        type: 'SpreadElement',
                        argument: {type: 'Identifier', name: 'props'}
                      }
                    ]
                  }
                }
              ],
              sourceType: 'module'
            }
          }
        }
      ],
      children: []
    },
    {
      type: 'paragraph',
      children: [
        {
          type: 'mdxJsxTextElement',
          name: 'abbr',
          attributes: [
            {
              type: 'mdxJsxAttribute',
              name: 'title',
              value: 'Hypertext Markup Language'
            }
          ],
          children: [{type: 'text', value: 'HTML'}]
        },
        {type: 'text', value: ' is a lovely language.'}
      ]
    }
  ]
}
<Box>
  *   a list
</Box>

<MyComponent {...props} />

<abbr title="Hypertext Markup Language">HTML</abbr> is a lovely language.

API

This package exports the identifiers mdxJsxFromMarkdown and mdxJsxToMarkdown. There is no default export.

mdxJsxFromMarkdown()

Create an extension for mdast-util-from-markdown to enable MDX JSX.

Returns

Extension for mdast-util-from-markdown to enable MDX JSX (FromMarkdownExtension).

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

mdxJsxToMarkdown(options?)

Create an extension for mdast-util-to-markdown to enable MDX JSX.

This extension configures mdast-util-to-markdown with options.fences: true and options.resourceLink: true too, do not overwrite them!

Parameters
Returns

Extension for mdast-util-to-markdown to enable MDX JSX (FromMarkdownExtension).

MdxJsxAttribute

MDX JSX attribute with a key (TypeScript type).

Type
import type {Literal} from 'mdast'

interface MdxJsxAttribute extends Literal {
  type: 'mdxJsxAttribute'
  name: string
  value?: MdxJsxAttributeValueExpression | string | null | undefined
}

MdxJsxAttributeValueExpression

MDX JSX attribute value set to an expression (TypeScript type).

Type
import type {Program} from 'estree-jsx'
import type {Literal} from 'mdast'

interface MdxJsxAttributeValueExpression extends Literal {
  type: 'mdxJsxAttributeValueExpression'
  data?: {estree?: Program | null | undefined} & Literal['data']
}

MdxJsxExpressionAttribute

MDX JSX attribute as an expression (TypeScript type).

Type
import type {Program} from 'estree-jsx'
import type {Literal} from 'mdast'

interface MdxJsxExpressionAttribute extends Literal {
  type: 'mdxJsxExpressionAttribute'
  data?: {estree?: Program | null | undefined} & Literal['data']
}

MdxJsxFlowElement

MDX JSX element node, occurring in flow (block) (TypeScript type).

Type
import type {BlockContent, DefinitionContent, Parent} from 'mdast'

export interface MdxJsxFlowElement extends Parent {
  type: 'mdxJsxFlowElement'
  name: string | null
  attributes: Array<MdxJsxAttribute | MdxJsxExpressionAttribute>
  children: Array<BlockContent | DefinitionContent>
}

MdxJsxFlowElementHast

Same as MdxJsxFlowElement, but registered with @types/hast (TypeScript type).

Type
import type {ElementContent, Parent} from 'hast'

export interface MdxJsxFlowElementHast extends Parent {
  type: 'mdxJsxFlowElement'
  name: string | null
  attributes: Array<MdxJsxAttribute | MdxJsxExpressionAttribute>
  children: Array<ElementContent>
}

MdxJsxTextElement

MDX JSX element node, occurring in text (phrasing) (TypeScript type).

Type
import type {Parent, PhrasingContent} from 'mdast'

export interface MdxJsxTextElement extends Parent {
  type: 'mdxJsxTextElement'
  name: string | null
  attributes: Array<MdxJsxAttribute | MdxJsxExpressionAttribute>
  children: Array<PhrasingContent>
}

MdxJsxTextElementHast

Same as MdxJsxTextElement, but registered with @types/hast (TypeScript type).

Type
import type {ElementContent, Parent} from 'hast'

export interface MdxJsxTextElementHast extends Parent {
  type: 'mdxJsxTextElement'
  name: string | null
  attributes: Array<MdxJsxAttribute | MdxJsxExpressionAttribute>
  children: Array<ElementContent>
}

ToMarkdownOptions

Configuration (TypeScript type).

Fields
  • quote ('"' or "'", default: '"') — preferred quote to use around attribute values
  • quoteSmart (boolean, default: false) — use the other quote if that results in less bytes
  • tightSelfClosing (boolean, default: false) — do not use an extra space when closing self-closing elements: <img/> instead of <img />
  • printWidth (number, default: Infinity) — try and wrap syntax at this width. When set to a finite number (say, 80), the formatter will print attributes on separate lines when a tag doesnt fit on one line. The normal behavior is to print attributes with spaces between them instead of line endings

HTML

MDX JSX has no representation in HTML. Though, when you are dealing with MDX, you will likely go through hast. You can enable passing MDX JSX through to hast by configuring mdast-util-to-hast with passThrough: ['mdxJsxFlowElement', 'mdxJsxTextElement'].

Syntax

See Syntax in micromark-extension-mdx-jsx.

Syntax tree

The following interfaces are added to mdast by this utility.

Nodes

MdxJsxFlowElement

interface MdxJsxFlowElement <: Parent {
  type: 'mdxJsxFlowElement'
}

MdxJsxFlowElement includes MdxJsxElement

MdxJsxFlowElement (Parent) represents JSX in flow (block). It can be used where flow content is expected. It includes the mixin MdxJsxElement.

For example, the following markdown:

<w x="y">
  z
</w>

Yields:

{
  type: 'mdxJsxFlowElement',
  name: 'w',
  attributes: [{type: 'mdxJsxAttribute', name: 'x', value: 'y'}],
  children: [{type: 'paragraph', children: [{type: 'text', value: 'z'}]}]
}

MdxJsxTextElement

interface MdxJsxTextElement <: Parent {
  type: 'mdxJsxTextElement'
}

MdxJsxTextElement includes MdxJsxElement

MdxJsxTextElement (Parent) represents JSX in text (span, inline). It can be used where phrasing content is expected. It includes the mixin MdxJsxElement.

For example, the following markdown:

a <b c>d</b> e.

Yields:

{
  type: 'mdxJsxTextElement',
  name: 'b',
  attributes: [{type: 'mdxJsxAttribute', name: 'c', value: null}],
  children: [{type: 'text', value: 'd'}]
}

Mixin

MdxJsxElement

interface mixin MdxJsxElement {
  name: string?
  attributes: [MdxJsxExpressionAttribute | MdxJsxAttribute]
}

interface MdxJsxExpressionAttribute <: Literal {
  type: 'mdxJsxExpressionAttribute'
}

interface MdxJsxAttribute <: Node {
  type: 'mdxJsxAttribute'
  name: string
  value: MdxJsxAttributeValueExpression | string?
}

interface MdxJsxAttributeValueExpression <: Literal {
  type: 'mdxJsxAttributeValueExpression'
}

MdxJsxElement represents a JSX element.

The name field can be present and represents an identifier. Without name, the element represents a fragment, in which case no attributes must be present.

The attributes field represents information associated with the node. The value of the attributes field is a list of MdxJsxExpressionAttribute and MdxJsxAttribute nodes.

MdxJsxExpressionAttribute represents an expression (typically in a programming language) that when evaluated results in multiple attributes.

MdxJsxAttribute represents a single attribute. The name field must be present. The value field can be present, in which case it is either a string (a static value) or an expression (typically in a programming language) that when evaluated results in an attribute value.

Content model

FlowContent (MDX JSX)
type MdxJsxFlowContent = MdxJsxFlowElement | FlowContent
PhrasingContent (MDX JSX)
type MdxJsxPhrasingContent = MdxJsxTextElement | PhrasingContent

Types

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

It also registers the node types with @types/mdast and @types/hast. If youre 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-jsx')}
 */

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

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

visit(tree, function (node) {
  // `node` can now be one of the JSX nodes.
})

Compatibility

Projects maintained by the unified collective are compatible with maintained versions of Node.js.

When we cut a new major release, we drop support for unmaintained versions of Node. This means we try to keep the current release line, mdast-util-mdx-jsx@^3, compatible with Node.js 16.

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

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