Thanks to visit codestin.com
Credit goes to www.11ty.dev

Skip to navigation Skip to main content

MDXAdded in v3.0.0

MDX is an extension of Markdown that adds JavaScript support and embedded components using JSX syntax. It can be a powerful language for writing content if you intend to include interactive components or intermix text with elements.

Eleventy Short Name File Extension npm Package
mdx .mdx @mdx-js/mdx
  • Related languages: Markdown, JSX, Custom
  • While Markdown files are preprocessed as Liquid, MDX files are not preprocessed by any other template syntax.
  • The Markdown in MDX files is parsed and transformed using Remark, which is different from Eleventy's default Markdown parser, markdown-it. Changes to Markdown options won't affect MDX, and output can be different from the same Markdown input.
MDX requires ESM. This means your project package.json must contain "type": "module" or your configuration file must use the .mjs file extension, e.g. eleventy.config.mjs.

Configuration

The following configuration will read *.mdx files with full compatibility for front matter (in .mdx files!). GitHub #3760.

eleventy.config.js
import {pathToFileURL} from "node:url";
import {evaluate} from "@mdx-js/mdx";
import {renderToStaticMarkup} from "react-dom/server";
import * as runtime from "react/jsx-runtime";

export default function(eleventyConfig) {
	eleventyConfig.addExtension("mdx", {
		compile: async (str, inputPath) => {
			const { default: mdxContent } = await evaluate(str, {
				...runtime,
				baseUrl: pathToFileURL(inputPath)
			});

			return async function(data) {
				let res = await mdxContent(data);
				return renderToStaticMarkup(res);
			}
		}
	});
};

Now run Eleventy and tell it to process mdx files:

npx @11ty/eleventy --formats=mdx

Alternatively, you can add eleventyConfig.addTemplateFormats("mdx") to your configuration file.

Example

sample.mdx
---
key: World
---
export function Exclaim(props) {
  return <>{props.target}!!!</>
}

# Hello from <Exclaim target={props.key} />

The above is rendered as <h1>Hello, World!!!</h1>.

Read more on the What is MDX? docs.

Alternate Configuration: use MDX Loader

Added in v3.0.0MDX also provides a Node.js loader (@mdx-js/node-loader on npm). This approach may be marginally faster but will not include support for Front Matter in .mdx files.

eleventy.config.js
import {register} from 'node:module';
import {renderToStaticMarkup} from 'react-dom/server'

register('@mdx-js/node-loader', import.meta.url);

export default function(eleventyConfig) {
	eleventyConfig.addExtension("mdx", {
		key: "11ty.js",
		compile: () => {
			return async function(data) {
				let content = await this.defaultRenderer(data);
				return renderToStaticMarkup(content);
			};
		}
	});
};

Community Contributions