Consider the following example Markdown document (say, src/blog/blog-post.md):
#
Hello MDX!
<figure class="figure">
<object data="figure.svg" type="image/svg+xml"></object>
<figcaption>An illustration of MDX in Markdown.</figcaption>
</figure>
We can write a Figure
component based on this in JSX, such as the following:
// src/components/figure.jsx
import
React
from
"react"
export
const
Figure
=
props
=>
{
return
(
<
figure
className
=
"chart"
>
<
object
data
=
{
props
.
data
}
type
=
"image/svg+xml"
></
object
>
<
figcaption
>{
props
.
caption
}</
figcaption
>
</
figure
>
)
}
Now, we can insert this Figure
component into the same Markdown document, src/blog/blog-post.md, using MDX:
import { Figure } from './components/Figure';
#
Hello MDX!
<Figure data="figure.svg" caption="An illustration of MDX in Markdown." />
The Gatsby ecosystem makes available a starter, gatsby-starter-mdx-basic
, to add MDX support instantly to a new Gatsby site. To spin up a new Gatsby site using this starter, execute the following command:
$
gatsby
new
gtdg-ch13-mdx
gatsbyjs/gatsby-starter-mdx-basic
It’s also possible to leverage MDX within an existing Gatsby site by adding certain dependencies, by executing the following command. Remember that sourcing data in Gatsby sites from Markdown files also requires gatsby-source-filesystem
, which we install here as well:
$
npm
install
gatsby-plugin-mdx
@mdx-js/mdx
@mdx-js/react
\
gatsby-source-filesystem
Then, add the gatsby-plugin-mdx
plugin to gatsby-config.js:
module
.
exports
=
{
plugins
:
[
// ....
`gatsby-plugin-mdx`
,
],
}
To set relevant configuration options for your requirements, add an options
object:
module
.
exports
=
{
plugins
:
[
// ....
{
resolve
:
`gatsby-plugin-mdx`
,
options
:
{
// Options for gatsby-plugin-mdx
}
}
],
}
Table 13-1 outlines the relevant configuration options.
Key | Default | Description |
---|---|---|
extensions | [".mdx"] | Configure the file extensions that gatsby-plugin-mdx will process. |
defaultLayouts | {} | Set the layout components for MDX source types. |
gatsbyRemarkPlugins | [] | Use Gatsby-specific plugins for Remark (a Markdown processor). |
remarkPlugins | [] | Specify Remark (a Markdown processor) plugins. |
rehypePlugins | [] | Specify Rehype (an HTML processor) plugins. |
mediaTypes | ["text/markdown", "text/x-markdown"] | Determine which media types are processed by MDX. |
shouldBlockNodeFromTransformation | (node) => false | Disable MDX transformation for nodes where this function returns true . |
commonmark | false | Use CommonMark (a Markdown specification). |
NOTE
For more information about MDX, consult the MDX website and the MDX plugin documentation for Gatsby. For more information about performing migrations from Remark (a Markdown processor) to MDX, consult the Gatsby documentation’s guide to migrating Remark to MDX.
Leave a Reply