MDX


Plugins

Since MDX uses the remark/rehype ecosystems, you can use plugins to modify the AST at different stages of the transpilation process.

Transpilation

The MDX transpilation flow consists of six steps, ultimately resulting in JSX that can be used in React/Preact/etc.

  1. Parse: Text => MDAST
  2. Transpile: MDAST => MDXAST
  3. Transform: MDX/Remark plugins applied to AST
  4. Transpile: MDXAST => MDXHAST
  5. Transform: Hyperscript plugins applied to AST
  6. Transpile: MDXHAST => JSX

Options

NameTypeRequiredDescription
mdPluginsArray[]falseArray of remark plugins to manipulate the MDAST
hastPluginsArray[]falseArray of rehype plugins to manipulate the MDXHAST

Specifying plugins

Plugins need to be passed to MDX core library, this is often as options to your loader:

const images = require('remark-images')
const emoji = require('remark-emoji')

module.exports = {
  module: {
    rules: [
      {
        test: /.mdx?$/,
        use: [
          {
            loader: 'babel-loader'
          },
          {
            loader: '@mdx-js/loader',
            options: {
              mdPlugins: [images, emoji]
            }
          }
        ]
      }
    ]
  }
}

Though if you're using MDX directly, they can be passed like so:

const fs = require('fs')
const mdx = require('@mdx-js/mdx')
const images = require('remark-images')
const emoji = require('remark-emoji')

const mdxText = fs.readFileSync('hello.mdx', 'utf8')
const jsx = mdx.sync(mdxText, {
  mdPlugins: [images, emoji]
})

Plugin options

If a plugin needs specific options, use the [plugin, pluginOptions] syntax.

mdx.sync(mdxText, {
  mdPlugins: [
    images,
    [emoji, { padSpaceAfter: true }]
})

The following example ensures that padSpaceAfter is only passed as options to the emoji plugin.