CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/npm-mdx-js--mdx

MDX compiler that transforms MDX documents into JavaScript

Overall
score

97%

Overview
Eval results
Files

evaluation.mddocs/

Evaluation and Runtime

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.

Capabilities

Evaluate Function

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 />);

EvaluateSync Function

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
});

Run Function

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
});

RunSync Function

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

EvaluateOptions Interface

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;
}

RunOptions Interface

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;
}

Runtime Types

JSX Runtime Types

/** 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;

Component Context

/** 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 Output

/** Module returned by evaluation functions */
interface MDXModule {
  /** Default exported MDX component */
  default: ComponentType<any>;
  
  /** Any other named exports from the MDX */
  [key: string]: any;
}

Runtime Integration Examples

React Integration

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>
  })
});

Preact Integration

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
});

Vue Integration

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'
});

Custom Components

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
});

Error Handling

Evaluation functions can throw errors for:

  • Missing required options: Fragment, jsx functions not provided
  • Compilation errors: Invalid MDX syntax or JSX
  • Runtime errors: Errors during component execution
  • Import errors: Failed module imports in MDX
  • Component errors: Errors in custom components
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);
  }
}

Performance Considerations

  • Caching: For frequently used MDX, consider caching compiled results
  • Component Reuse: Minimize component recreation by memoizing useMDXComponents
  • Development Mode: Only use development mode during development for better performance in production
// 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--mdx

docs

compilation.md

evaluation.md

index.md

processor.md

tile.json