0
# Evaluation and Runtime
1
2
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.
3
4
⚠️ **Security Warning**: These functions use `eval()` internally. Only use with trusted content.
5
6
## Capabilities
7
8
### Evaluate Function
9
10
Compiles and runs MDX code in a single operation, returning a module with the default component and any exports.
11
12
```typescript { .api }
13
/**
14
* Compile and run MDX code
15
* @param file - MDX document to parse and execute
16
* @param options - Required evaluation configuration with JSX runtime
17
* @returns Promise resolving to MDX module with default component
18
*/
19
function evaluate(
20
file: Compatible,
21
options: EvaluateOptions
22
): Promise<MDXModule>;
23
```
24
25
**Usage Examples:**
26
27
```typescript
28
import { evaluate } from "@mdx-js/mdx";
29
import * as runtime from "react/jsx-runtime";
30
31
// Basic evaluation
32
const mdxSource = `
33
# Hello World
34
35
export const metadata = { title: "Example" };
36
37
<div>This is JSX content</div>
38
`;
39
40
const { default: Component, metadata } = await evaluate(mdxSource, {
41
...runtime,
42
baseUrl: import.meta.url
43
});
44
45
// Render the component
46
import { createRoot } from 'react-dom/client';
47
const root = createRoot(document.getElementById('root'));
48
root.render(<Component />);
49
```
50
51
### EvaluateSync Function
52
53
Synchronously compiles and runs MDX code. Use the async `evaluate` when possible for better performance.
54
55
```typescript { .api }
56
/**
57
* Synchronously compile and run MDX code
58
* @param file - MDX document to parse and execute
59
* @param options - Required evaluation configuration with JSX runtime
60
* @returns MDX module with default component
61
*/
62
function evaluateSync(
63
file: Compatible,
64
options: EvaluateOptions
65
): MDXModule;
66
```
67
68
**Usage Examples:**
69
70
```typescript
71
import { evaluateSync } from "@mdx-js/mdx";
72
import * as runtime from "react/jsx-runtime";
73
74
const { default: Component } = evaluateSync('# Hello\n\nThis is **bold**.', {
75
...runtime,
76
baseUrl: import.meta.url
77
});
78
```
79
80
### Run Function
81
82
Executes JavaScript code compiled with `outputFormat: 'function-body'`, providing lower-level control over the execution process.
83
84
```typescript { .api }
85
/**
86
* Run code compiled with outputFormat: 'function-body'
87
* @param code - JavaScript function body to execute
88
* @param options - Required runtime configuration
89
* @returns Promise resolving to MDX module
90
*/
91
function run(
92
code: {toString(): string},
93
options: RunOptions
94
): Promise<MDXModule>;
95
```
96
97
**Usage Examples:**
98
99
```typescript
100
import { compile, run } from "@mdx-js/mdx";
101
import * as runtime from "react/jsx-runtime";
102
103
// Two-step process: compile then run
104
const compiled = await compile('# Hello World', {
105
outputFormat: 'function-body'
106
});
107
108
const { default: Component } = await run(compiled, {
109
...runtime,
110
baseUrl: import.meta.url
111
});
112
```
113
114
### RunSync Function
115
116
Synchronously executes compiled JavaScript code.
117
118
```typescript { .api }
119
/**
120
* Synchronously run compiled JavaScript code
121
* @param code - JavaScript function body to execute
122
* @param options - Required runtime configuration
123
* @returns MDX module with default component
124
*/
125
function runSync(
126
code: {toString(): string},
127
options: RunOptions
128
): MDXModule;
129
```
130
131
## Configuration
132
133
### EvaluateOptions Interface
134
135
Configuration for `evaluate` and `evaluateSync` functions, combining compilation and runtime options.
136
137
```typescript { .api }
138
interface EvaluateOptions {
139
/** Required JSX Fragment component */
140
Fragment: Fragment;
141
142
/** JSX function for production mode (required unless development: true) */
143
jsx?: Jsx;
144
145
/** JSX function for development mode (required if development: true) */
146
jsxDEV?: JsxDev;
147
148
/** JSX function for dynamic children in production mode */
149
jsxs?: Jsx;
150
151
/** Base URL for resolving imports */
152
baseUrl?: URL | string;
153
154
/** Function to get components from context */
155
useMDXComponents?: UseMdxComponents;
156
157
/** Whether to use development mode with enhanced debugging */
158
development?: boolean;
159
160
/** Format of input content */
161
format?: 'md' | 'mdx';
162
163
/** Remark plugins for markdown processing */
164
remarkPlugins?: PluggableList;
165
166
/** Rehype plugins for HTML processing */
167
rehypePlugins?: PluggableList;
168
169
/** Recma plugins for JavaScript generation */
170
recmaPlugins?: PluggableList;
171
172
/** Source map generator for debugging */
173
SourceMapGenerator?: typeof SourceMapGenerator;
174
}
175
```
176
177
### RunOptions Interface
178
179
Configuration for `run` and `runSync` functions.
180
181
```typescript { .api }
182
interface RunOptions {
183
/** Required JSX Fragment component */
184
Fragment: Fragment;
185
186
/** JSX function for production mode */
187
jsx?: Jsx;
188
189
/** JSX function for development mode */
190
jsxDEV?: JsxDev;
191
192
/** JSX function for dynamic children */
193
jsxs?: Jsx;
194
195
/** Base URL for resolving imports */
196
baseUrl?: URL | string;
197
198
/** Function to get components from context */
199
useMDXComponents?: UseMdxComponents;
200
}
201
```
202
203
## Runtime Types
204
205
### JSX Runtime Types
206
207
```typescript { .api }
208
/** Fragment component for JSX fragments */
209
type Fragment = ComponentType<{children?: ReactNode}>;
210
211
/** JSX function for creating elements */
212
type Jsx = (
213
type: any,
214
props: any,
215
key?: any
216
) => any;
217
218
/** Development JSX function with additional debugging info */
219
type JsxDev = (
220
type: any,
221
props: any,
222
key?: any,
223
isStaticChildren?: boolean,
224
source?: any,
225
self?: any
226
) => any;
227
```
228
229
### Component Context
230
231
```typescript { .api }
232
/** Function to get components from context */
233
interface UseMdxComponents {
234
(): MDXComponents;
235
}
236
237
/** Component map for custom component overrides */
238
interface MDXComponents {
239
[key: string]: ComponentType<any>;
240
h1?: ComponentType<any>;
241
h2?: ComponentType<any>;
242
p?: ComponentType<any>;
243
a?: ComponentType<any>;
244
// ... other HTML elements
245
}
246
```
247
248
### Module Output
249
250
```typescript { .api }
251
/** Module returned by evaluation functions */
252
interface MDXModule {
253
/** Default exported MDX component */
254
default: ComponentType<any>;
255
256
/** Any other named exports from the MDX */
257
[key: string]: any;
258
}
259
```
260
261
## Runtime Integration Examples
262
263
### React Integration
264
265
```typescript
266
import { evaluate } from "@mdx-js/mdx";
267
import * as runtime from "react/jsx-runtime";
268
269
const { default: Content } = await evaluate(mdxSource, {
270
...runtime,
271
baseUrl: import.meta.url,
272
useMDXComponents: () => ({
273
h1: ({ children }) => <h1 className="title">{children}</h1>,
274
Button: ({ children, ...props }) => <button {...props}>{children}</button>
275
})
276
});
277
```
278
279
### Preact Integration
280
281
```typescript
282
import { evaluate } from "@mdx-js/mdx";
283
import { Fragment, jsx, jsxs } from "preact/jsx-runtime";
284
285
const { default: Content } = await evaluate(mdxSource, {
286
Fragment,
287
jsx,
288
jsxs,
289
baseUrl: import.meta.url
290
});
291
```
292
293
### Vue Integration
294
295
```typescript
296
import { evaluate } from "@mdx-js/mdx";
297
import { Fragment, jsx, jsxs } from "vue/jsx-runtime";
298
299
const { default: Content } = await evaluate(mdxSource, {
300
Fragment,
301
jsx,
302
jsxs,
303
baseUrl: import.meta.url,
304
development: process.env.NODE_ENV === 'development'
305
});
306
```
307
308
### Custom Components
309
310
```typescript
311
import { evaluate } from "@mdx-js/mdx";
312
import * as runtime from "react/jsx-runtime";
313
314
const customComponents = {
315
Alert: ({ type, children }) => (
316
<div className={`alert alert-${type}`}>
317
{children}
318
</div>
319
),
320
CodeBlock: ({ language, children }) => (
321
<pre className={`language-${language}`}>
322
<code>{children}</code>
323
</pre>
324
)
325
};
326
327
const { default: Content } = await evaluate(mdxSource, {
328
...runtime,
329
baseUrl: import.meta.url,
330
useMDXComponents: () => customComponents
331
});
332
```
333
334
## Error Handling
335
336
Evaluation functions can throw errors for:
337
338
- **Missing required options**: Fragment, jsx functions not provided
339
- **Compilation errors**: Invalid MDX syntax or JSX
340
- **Runtime errors**: Errors during component execution
341
- **Import errors**: Failed module imports in MDX
342
- **Component errors**: Errors in custom components
343
344
```typescript
345
try {
346
const { default: Content } = await evaluate(mdxSource, {
347
...runtime,
348
baseUrl: import.meta.url
349
});
350
} catch (error) {
351
if (error.message.includes('Expected `Fragment`')) {
352
console.error('Missing required Fragment in runtime options');
353
} else if (error.name === 'VFileMessage') {
354
console.error('MDX compilation error:', error.message);
355
} else {
356
console.error('Runtime error:', error);
357
}
358
}
359
```
360
361
## Performance Considerations
362
363
- **Caching**: For frequently used MDX, consider caching compiled results
364
- **Component Reuse**: Minimize component recreation by memoizing `useMDXComponents`
365
- **Development Mode**: Only use development mode during development for better performance in production
366
367
```typescript
368
// Performance optimization example
369
const componentCache = new Map();
370
371
function getCachedComponent(mdxSource) {
372
if (componentCache.has(mdxSource)) {
373
return componentCache.get(mdxSource);
374
}
375
376
const componentPromise = evaluate(mdxSource, runtimeOptions);
377
componentCache.set(mdxSource, componentPromise);
378
return componentPromise;
379
}
380
```