πŸŽ‰These docs are for v1 (currently in beta) β€” read the v0 docs β†’
MDX logoMDX v1.0.0-alpha.17
GitHub logo

Transform Content

With MDX you can interact with or manipulate raw MDX content. Since MDX is a part of the unified ecosystem, there are many utilities you can use to work with MDX.

You can utilize to-vfile to read and write MDX files and you can leverage remark and remark-mdx to parse and process MDX content. The remark-mdx library is a parsing extension to enhance the Markdown AST to understand MDX (resulting in MDXAST), giving you access and insight to MDX attributes, namely imports, exports, and jsx.

Let’s see an example of what we have explained so far.

Say we have the following file, example.mdx:

import Component from 'Component';
export const meta = {
prop: 'value'
};
# Title
Content.
<Component />

And our script, example.js, looks as follows:

const {read, write} = require('to-vfile')
const remark = require('remark');
const mdx = require('remark-mdx');
(async () => {
const path = './example.mdx';
const file = await read(path);
const contents = await remark()
.use(mdx)
.use(() => (tree) => {
console.log(tree)
})
.process(file);
await write({
path,
contents
})
})();

Now, running node example.js yields:

{
type: "root",
children: [
{
type: "import",
value: "import Component from 'Component';",
position: [Object]
},
{
type: "export",
value: "export const meta = {\n prop: 'value'\n};",
position: [Object]
},
{ type: "heading", depth: 1, children: [Array], position: [Object] },
{ type: "paragraph", children: [Array], position: [Object] },
{ type: "jsx", value: "<Component />", position: [Object] }
],
position: {
start: { line: 1, column: 1, offset: 0 },
end: { line: 12, column: 1, offset: 113 }
}
}

From here, you can continue to write your own plugin or use any of the remark plugins parse or manipulate MDX content.

This technique allows you to use things like remark-toc to add a generated table of contents based on the other content in the MDX file or remark-mdx-metadata to externally modify MDX metadata and save the modified content back to the original file.

Edit this page on GitHub
Next:
Getting Started