MDX compiler that transforms MDX documents into JavaScript
Overall
score
97%
Safe evaluation and runtime execution of compiled MDX code. These functions compile and immediately execute MDX content, making them ideal for development environments, dynamic content scenarios, and situations where you need immediate component rendering.
⚠️ Security Warning: These functions use eval() internally. Only use with trusted content.
Compiles and runs MDX code in a single operation, returning a module with the default component and any exports.
/**
* Compile and run MDX code
* @param file - MDX document to parse and execute
* @param options - Required evaluation configuration with JSX runtime
* @returns Promise resolving to MDX module with default component
*/
function evaluate(
file: Compatible,
options: EvaluateOptions
): Promise<MDXModule>;Usage Examples:
import { evaluate } from "@mdx-js/mdx";
import * as runtime from "react/jsx-runtime";
// Basic evaluation
const mdxSource = `
# Hello World
export const metadata = { title: "Example" };
<div>This is JSX content</div>
`;
const { default: Component, metadata } = await evaluate(mdxSource, {
...runtime,
baseUrl: import.meta.url
});
// Render the component
import { createRoot } from 'react-dom/client';
const root = createRoot(document.getElementById('root'));
root.render(<Component />);Synchronously compiles and runs MDX code. Use the async evaluate when possible for better performance.
/**
* Synchronously compile and run MDX code
* @param file - MDX document to parse and execute
* @param options - Required evaluation configuration with JSX runtime
* @returns MDX module with default component
*/
function evaluateSync(
file: Compatible,
options: EvaluateOptions
): MDXModule;Usage Examples:
import { evaluateSync } from "@mdx-js/mdx";
import * as runtime from "react/jsx-runtime";
const { default: Component } = evaluateSync('# Hello\n\nThis is **bold**.', {
...runtime,
baseUrl: import.meta.url
});Executes JavaScript code compiled with outputFormat: 'function-body', providing lower-level control over the execution process.
/**
* Run code compiled with outputFormat: 'function-body'
* @param code - JavaScript function body to execute
* @param options - Required runtime configuration
* @returns Promise resolving to MDX module
*/
function run(
code: {toString(): string},
options: RunOptions
): Promise<MDXModule>;Usage Examples:
import { compile, run } from "@mdx-js/mdx";
import * as runtime from "react/jsx-runtime";
// Two-step process: compile then run
const compiled = await compile('# Hello World', {
outputFormat: 'function-body'
});
const { default: Component } = await run(compiled, {
...runtime,
baseUrl: import.meta.url
});Synchronously executes compiled JavaScript code.
/**
* Synchronously run compiled JavaScript code
* @param code - JavaScript function body to execute
* @param options - Required runtime configuration
* @returns MDX module with default component
*/
function runSync(
code: {toString(): string},
options: RunOptions
): MDXModule;Configuration for evaluate and evaluateSync functions, combining compilation and runtime options.
interface EvaluateOptions {
/** Required JSX Fragment component */
Fragment: Fragment;
/** JSX function for production mode (required unless development: true) */
jsx?: Jsx;
/** JSX function for development mode (required if development: true) */
jsxDEV?: JsxDev;
/** JSX function for dynamic children in production mode */
jsxs?: Jsx;
/** Base URL for resolving imports */
baseUrl?: URL | string;
/** Function to get components from context */
useMDXComponents?: UseMdxComponents;
/** Whether to use development mode with enhanced debugging */
development?: boolean;
/** Format of input content */
format?: 'md' | 'mdx';
/** Remark plugins for markdown processing */
remarkPlugins?: PluggableList;
/** Rehype plugins for HTML processing */
rehypePlugins?: PluggableList;
/** Recma plugins for JavaScript generation */
recmaPlugins?: PluggableList;
/** Source map generator for debugging */
SourceMapGenerator?: typeof SourceMapGenerator;
}Configuration for run and runSync functions.
interface RunOptions {
/** Required JSX Fragment component */
Fragment: Fragment;
/** JSX function for production mode */
jsx?: Jsx;
/** JSX function for development mode */
jsxDEV?: JsxDev;
/** JSX function for dynamic children */
jsxs?: Jsx;
/** Base URL for resolving imports */
baseUrl?: URL | string;
/** Function to get components from context */
useMDXComponents?: UseMdxComponents;
}/** Fragment component for JSX fragments */
type Fragment = ComponentType<{children?: ReactNode}>;
/** JSX function for creating elements */
type Jsx = (
type: any,
props: any,
key?: any
) => any;
/** Development JSX function with additional debugging info */
type JsxDev = (
type: any,
props: any,
key?: any,
isStaticChildren?: boolean,
source?: any,
self?: any
) => any;/** Function to get components from context */
interface UseMdxComponents {
(): MDXComponents;
}
/** Component map for custom component overrides */
interface MDXComponents {
[key: string]: ComponentType<any>;
h1?: ComponentType<any>;
h2?: ComponentType<any>;
p?: ComponentType<any>;
a?: ComponentType<any>;
// ... other HTML elements
}/** Module returned by evaluation functions */
interface MDXModule {
/** Default exported MDX component */
default: ComponentType<any>;
/** Any other named exports from the MDX */
[key: string]: any;
}import { evaluate } from "@mdx-js/mdx";
import * as runtime from "react/jsx-runtime";
const { default: Content } = await evaluate(mdxSource, {
...runtime,
baseUrl: import.meta.url,
useMDXComponents: () => ({
h1: ({ children }) => <h1 className="title">{children}</h1>,
Button: ({ children, ...props }) => <button {...props}>{children}</button>
})
});import { evaluate } from "@mdx-js/mdx";
import { Fragment, jsx, jsxs } from "preact/jsx-runtime";
const { default: Content } = await evaluate(mdxSource, {
Fragment,
jsx,
jsxs,
baseUrl: import.meta.url
});import { evaluate } from "@mdx-js/mdx";
import { Fragment, jsx, jsxs } from "vue/jsx-runtime";
const { default: Content } = await evaluate(mdxSource, {
Fragment,
jsx,
jsxs,
baseUrl: import.meta.url,
development: process.env.NODE_ENV === 'development'
});import { evaluate } from "@mdx-js/mdx";
import * as runtime from "react/jsx-runtime";
const customComponents = {
Alert: ({ type, children }) => (
<div className={`alert alert-${type}`}>
{children}
</div>
),
CodeBlock: ({ language, children }) => (
<pre className={`language-${language}`}>
<code>{children}</code>
</pre>
)
};
const { default: Content } = await evaluate(mdxSource, {
...runtime,
baseUrl: import.meta.url,
useMDXComponents: () => customComponents
});Evaluation functions can throw errors for:
try {
const { default: Content } = await evaluate(mdxSource, {
...runtime,
baseUrl: import.meta.url
});
} catch (error) {
if (error.message.includes('Expected `Fragment`')) {
console.error('Missing required Fragment in runtime options');
} else if (error.name === 'VFileMessage') {
console.error('MDX compilation error:', error.message);
} else {
console.error('Runtime error:', error);
}
}useMDXComponents// Performance optimization example
const componentCache = new Map();
function getCachedComponent(mdxSource) {
if (componentCache.has(mdxSource)) {
return componentCache.get(mdxSource);
}
const componentPromise = evaluate(mdxSource, runtimeOptions);
componentCache.set(mdxSource, componentPromise);
return componentPromise;
}Install with Tessl CLI
npx tessl i tessl/npm-mdx-js--mdxevals
scenario-1
scenario-2
scenario-3
scenario-4
scenario-5
scenario-6
scenario-7
scenario-8
scenario-9
scenario-10