MDX is a JSX in Markdown loader, parser, and renderer for ambitious projects. It combines the readability of Markdown with the expressivity of JSX. The best of both worlds. 🌐
- Fast
- No runtime compilation
- Pluggable
- Element to React component mapping
- React component
import
/export
- Simpler image syntax
- Webpack loader
npm install --save-dev @mdx-js/loader @mdx-js/mdx
Note: mdx requires a version of node that is >=
v8.5
You'll need to specify the @mdx-js/loader
webpack loader and follow it with the babel-loader
:
module.exports = {
module: {
rules: [
{
test: /\.md$/,
use: ['babel-loader', '@mdx-js/loader']
}
]
}
}
Create an md file, hello.md
:
# Hello, world!
And import it from a component, pages/index.js
:
import React from 'react'
import Hello from '../hello.md'
export default () => <Hello />
Similarly to JSX, components can be rendered after an import
:
import Graph from './components/graph'
## Here's a graph
<Graph />
You can transclude Markdown files by importing one .md
file into another:
import License from './license.md'
import Contributing from './docs/contributing.md'
# Hello, world!
<License />
---
<Contributing />
You can use exports to export metadata like layout or authors. It's a mechanism for an imported MDX file to communicate with its parent. It works similarly to frontmatter, but uses ES2015 syntax.
import { fred, sue } from '../data/authors'
import Layout from '../components/with-blog-layout'
export const meta = {
authors: [fred, sue],
layout: Layout
}
You can pass in components for any html
element that Markdown compiles to.
This allows you to use your existing components and use CSS-in-JS like styled-components
.
import React from 'react'
import Hello from '../hello.md'
import {
Text,
Heading,
Code,
InlineCode
} from '../ui'
export default () =>
<Hello
components={{
h1: Heading,
p: Text,
code: Code,
inlineCode: InlineCode
}}
/>
Since MDX uses the remark/rehype ecosystems, you can use plugins to modify the AST at different stages of the transpilation process.
If you look at the next example, it shows you to pass plugins as options to the MDX loader.
Name | Type | Required | Description |
---|---|---|---|
mdPlugins |
Array[] | false |
Array of remark plugins to manipulate the MDXAST |
hastPlugins |
Array[] | false |
Array of rehype plugins to manipulate the MDXHAST |
If you're using the MDX library directly, you might want to process an MDX string synchronously.
const jsx = mdx.sync('# Hello, world!')
See the related projects in the MDX specification
- John Otander (@4lpine) – Compositor + Clearbit
- Tim Neutkens (@timneutkens) – ZEIT
- Guillermo Rauch (@rauchg) – ZEIT
- Brent Jackson (@jxnblk) – Compositor