By Titus Wormer
Using MDX
This article explains how to use MDX files in your project. It shows how you can pass props and how to importdefineor pass components. See § Getting started for how to integrate MDX into your project. To understand how the MDX format workswe recommend that you start with § What is MDX.
Contents
How MDX works
An integration compiles MDX syntax to JavaScript. Say we have an MDX documentexample.mdx:
export function Thing() {
return <>World</>
}
# Hello <Thing />
That’s roughly turned into the following JavaScript. The below might help to form a mental model:
/* @xRuntime automatic */
/* @xImportSource react */
export function Thing() {
return <>World</>
}
export default function MDXContent() {
return <h1>Hello <Thing /></h1>
}
function Thing(): JSX.Elementfunction MDXContent(): JSX.Element(property) JSX.IntrinsicElements.h1: React.DetailedHTMLProps<React.HTMLAttributes<HTMLHeadingElement>HTMLHeadingElement>function Thing(): JSX.Element(property) JSX.IntrinsicElements.h1: React.DetailedHTMLProps<React.HTMLAttributes<HTMLHeadingElement>HTMLHeadingElement>Some observations:
- The output is serialized JavaScript that still needs to be evaluated
- A comment is injected to configure how JSX is handled
- It’s a complete file with import/exports
- A component (
MDXContent) is exported
The actual output is:
import {Fragment as _Fragmentx as _xxs as _xs} from 'react/x-runtime'
export function Thing() {
return _x(_Fragment{children: 'World'})
}
function _createMdxContent(props) {
const _components = {h1: 'h1'...props.components}
return _xs(_components.h1{children: ['Hello '_x(Thing{})]})
}
export default function MDXContent(props = {}) {
const {wrapper: MDXLayout} = props.components || {}
return MDXLayout
? _x(MDXLayout{...propschildren: _x(_createMdxContent{...props})})
: _createMdxContent(props)
}
(alias) const Fragment: React.ExoticComponent<{
children?: React.ReactNode | undefined;
}>
export FragmentLets you group elements without a wrapper node.
- @see {@link https://react.dev/reference/react/Fragment React Docs}
- @example
import { Fragment } from 'react'; <Fragment> <td>Hello</td> <td>World</td> </Fragment> - @example
// Using the <></> shorthand syntax: <> <td>Hello</td> <td>World</td> </>
(alias) const _Fragment: React.ExoticComponent<{
children?: React.ReactNode | undefined;
}>
import _FragmentLets you group elements without a wrapper node.
- @see {@link https://react.dev/reference/react/Fragment React Docs}
- @example
import { Fragment } from 'react'; <Fragment> <td>Hello</td> <td>World</td> </Fragment> - @example
// Using the <></> shorthand syntax: <> <td>Hello</td> <td>World</td> </>
function x(type: React.ElementTypeprops: unknownkey?: React.Key): React.ReactElementCreate a React element.
You should not use this function directly. Use JSX and a transpiler instead.
(alias) function _x(type: React.ElementTypeprops: unknownkey?: React.Key): React.ReactElement
import _xCreate a React element.
You should not use this function directly. Use JSX and a transpiler instead.
function xs(type: React.ElementTypeprops: unknownkey?: React.Key): React.ReactElementCreate a React element.
You should not use this function directly. Use JSX and a transpiler instead.
(alias) function _xs(type: React.ElementTypeprops: unknownkey?: React.Key): React.ReactElement
import _xsCreate a React element.
You should not use this function directly. Use JSX and a transpiler instead.
function Thing(): React.ReactElement<anystring | React.JSXElementConstructor<any>>(alias) _x(type: React.ElementTypeprops: unknownkey?: React.Key): React.ReactElement
import _xCreate a React element.
You should not use this function directly. Use JSX and a transpiler instead.
(alias) const _Fragment: React.ExoticComponent<{
children?: React.ReactNode | undefined;
}>
import _FragmentLets you group elements without a wrapper node.
- @see {@link https://react.dev/reference/react/Fragment React Docs}
- @example
import { Fragment } from 'react'; <Fragment> <td>Hello</td> <td>World</td> </Fragment> - @example
// Using the <></> shorthand syntax: <> <td>Hello</td> <td>World</td> </>
(property) children: stringfunction _createMdxContent(props: any): React.ReactElement<anystring | React.JSXElementConstructor<any>>(parameter) props: anyconst _components: any(property) h1: string(parameter) props: anyany(alias) _xs(type: React.ElementTypeprops: unknownkey?: React.Key): React.ReactElement
import _xsCreate a React element.
You should not use this function directly. Use JSX and a transpiler instead.
const _components: anyany(property) children: (string | React.ReactElement<anystring | React.JSXElementConstructor<any>>)[](alias) _x(type: React.ElementTypeprops: unknownkey?: React.Key): React.ReactElement
import _xCreate a React element.
You should not use this function directly. Use JSX and a transpiler instead.
function Thing(): React.ReactElement<anystring | React.JSXElementConstructor<any>>function MDXContent(props?: {}): React.ReactElement<anystring | React.JSXElementConstructor<any>>(parameter) props: {}anyconst MDXLayout: any(parameter) props: {}anyconst MDXLayout: any(alias) _x(type: React.ElementTypeprops: unknownkey?: React.Key): React.ReactElement
import _xCreate a React element.
You should not use this function directly. Use JSX and a transpiler instead.
const MDXLayout: any(parameter) props: {}(property) children: React.ReactElement<anystring | React.JSXElementConstructor<any>>(alias) _x(type: React.ElementTypeprops: unknownkey?: React.Key): React.ReactElement
import _xCreate a React element.
You should not use this function directly. Use JSX and a transpiler instead.
function _createMdxContent(props: any): React.ReactElement<anystring | React.JSXElementConstructor<any>>(parameter) props: {}function _createMdxContent(props: any): React.ReactElement<anystring | React.JSXElementConstructor<any>>(parameter) props: {}Some more observations:
- JSX is compiled away to function calls and an import of React†
- The content component can be given
{components: {wrapper: MyLayout}}to wrap all content - The content component can be given
{components: {h1: MyComponent}}to use something else for the heading
† MDX is not coupled to React. You can also use it with PreactVueEmotionTheme UIetc. Both the classic and automatic JSX runtimes are supported.
MDX content
We just saw that MDX files are compiled to components. You can use those components like any other component in your framework of choice. Take this file:
# Hi!
It could be imported and used in a React app like so:
import {createRoot} from 'react-dom/client'
import Example from './example.mdx' // Assumes an integration is used to compile MDX -> JS.
const container = document.getElementById('root')
if (!container) throw new Error('Expected `root`')
const root = createRoot(container)
root.render(<Example />)
(alias) function createRoot(container: Containeroptions?: RootOptions): Root
import createRootcreateRoot lets you create a root to display React components inside a browser DOM node.
- @see {@link https://react.dev/reference/react-dom/client/createRoot API Reference for
createRoot}
(alias) function Example(props: MDXProps): Element
import ExampleAn function component which renders the MDX content using JSX.
- @param props This value is be available as the named variable
propsinside the MDX component. - @returns A JSX element. The meaning of this may depend on the project configuration. I.e. it could be a ReactPreactor Vuex element.
const container: HTMLElement | nullvar document: Document(method) Document.getElementById(elementId: string): HTMLElement | nullReturns a reference to the first object with the specified value of the ID attribute.
- @param elementId String that specifies the ID value.
const container: HTMLElement | nullvar Error: ErrorConstructor
new (message?: stringoptions?: ErrorOptions) => Error (+1 overload)const root: Root(alias) createRoot(container: Containeroptions?: RootOptions): Root
import createRootcreateRoot lets you create a root to display React components inside a browser DOM node.
- @see {@link https://react.dev/reference/react-dom/client/createRoot API Reference for
createRoot}
const container: HTMLElementconst root: Root(method) Root.render(children: React.ReactNode): void(alias) function Example(props: MDXProps): Element
import ExampleAn function component which renders the MDX content using JSX.
- @param props This value is be available as the named variable
propsinside the MDX component. - @returns A JSX element. The meaning of this may depend on the project configuration. I.e. it could be a ReactPreactor Vuex element.
The main content is exported as the default export. All other values are also exported. Take this example:
export function Thing() {
return <>World</>
}
# Hello <Thing />
It could be imported in the following ways:
// A namespace import to get everything:
import * as everything from './example.mdx' // Assumes an integration is used to compile MDX -> JS.
console.log(everything) // {Thing: [Function: Thing]default: [Function: MDXContent]}
// Default export shortcut and a named import specifier:
import Content{Thing} from './example.mdx'
console.log(Content) // [Function: MDXContent]
console.log(Thing) // [Function: Thing]
// Import specifier with another local name:
import {Thing as AnotherName} from './example.mdx'
console.log(AnotherName) // [Function: Thing]
(alias) module "*.mdx"
import everythingAn MDX file which exports a JSX component.
The default export of MDX files is a function which takes props and returns a JSX element. MDX files can export other identifiers from within the MDX file as welleither authored manually or automatically through plugins
It’s currently not possible for the other exports to be typed automatically. You can type them yourself with a TypeScript script which augments *.mdx modules. A script file is a file which doesn’t use top-level ESM syntaxbut ESM syntax is allowed inside the declared module.
This is typically useful for exports created by plugins. For example:
// mdx-custom.d.ts
declare module '*.mdx' {
import { Frontmatter } from 'my-frontmatter-types';
export const frontmatter: Frontmatter;
export const title: string;
}
The previous example added types to all .mdx files. To define types for a specific MDX filecreate a file with the same name but postfixed with .d.ts next to the MDX file.
For examplegiven the following MDX file my-component.mdx:
export const message = 'world';
# Hello {message}
Create the following file named my-component.mdx.d.ts in the same directory:
export { default } from '*.mdx';
export const message: string;
Note that this overwrites the declare module '*.mdx' { … } types from earlierwhich is why you also need to define the default export. You can also define your own default export type to narrow the accepted prop types of this specific file.
It should now be possible to import both the MDX component and the exported constant message.
namespace console
var console: ConsoleThe console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Consoleclass with methods such asconsole.log()console.error()andconsole.warn()that can be used to write to any Node. stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without callingrequire('console').
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemblenor are they consistently asynchronous like all other Node. streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello worldto stdout
console.log('hello %s''world');
// Prints: hello worldto stdout
console.error(new Error('Whoopssomething bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoopssomething bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to stderr
Example using the Console class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(outerr);
myConsole.log('hello world');
// Prints: hello worldto out
myConsole.log('hello %s''world');
// Prints: hello worldto out
myConsole.error(new Error('Whoopssomething bad happened'));
// Prints: [Error: Whoopssomething bad happened]to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to err
- @see source
(method) Console.log(message?: any...optionalParams: any[]): voidPrints to stdout with newline. Multiple arguments can be passedwith the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).
const count = 5;
console.log('count: %d'count);
// Prints: count: 5to stdout
console.log('count:'count);
// Prints: count: 5to stdout
See util.format() for more information.
- @since v0.1.100
(alias) module "*.mdx"
import everythingAn MDX file which exports a JSX component.
The default export of MDX files is a function which takes props and returns a JSX element. MDX files can export other identifiers from within the MDX file as welleither authored manually or automatically through plugins
It’s currently not possible for the other exports to be typed automatically. You can type them yourself with a TypeScript script which augments *.mdx modules. A script file is a file which doesn’t use top-level ESM syntaxbut ESM syntax is allowed inside the declared module.
This is typically useful for exports created by plugins. For example:
// mdx-custom.d.ts
declare module '*.mdx' {
import { Frontmatter } from 'my-frontmatter-types';
export const frontmatter: Frontmatter;
export const title: string;
}
The previous example added types to all .mdx files. To define types for a specific MDX filecreate a file with the same name but postfixed with .d.ts next to the MDX file.
For examplegiven the following MDX file my-component.mdx:
export const message = 'world';
# Hello {message}
Create the following file named my-component.mdx.d.ts in the same directory:
export { default } from '*.mdx';
export const message: string;
Note that this overwrites the declare module '*.mdx' { … } types from earlierwhich is why you also need to define the default export. You can also define your own default export type to narrow the accepted prop types of this specific file.
It should now be possible to import both the MDX component and the exported constant message.
(alias) function Content(props: MDXProps): Element
import ContentAn function component which renders the MDX content using JSX.
- @param props This value is be available as the named variable
propsinside the MDX component. - @returns A JSX element. The meaning of this may depend on the project configuration. I.e. it could be a ReactPreactor Vuex element.
(alias) function Thing(): JSX.Element
import Thingnamespace console
var console: ConsoleThe console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Consoleclass with methods such asconsole.log()console.error()andconsole.warn()that can be used to write to any Node. stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without callingrequire('console').
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemblenor are they consistently asynchronous like all other Node. streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello worldto stdout
console.log('hello %s''world');
// Prints: hello worldto stdout
console.error(new Error('Whoopssomething bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoopssomething bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to stderr
Example using the Console class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(outerr);
myConsole.log('hello world');
// Prints: hello worldto out
myConsole.log('hello %s''world');
// Prints: hello worldto out
myConsole.error(new Error('Whoopssomething bad happened'));
// Prints: [Error: Whoopssomething bad happened]to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to err
- @see source
(method) Console.log(message?: any...optionalParams: any[]): voidPrints to stdout with newline. Multiple arguments can be passedwith the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).
const count = 5;
console.log('count: %d'count);
// Prints: count: 5to stdout
console.log('count:'count);
// Prints: count: 5to stdout
See util.format() for more information.
- @since v0.1.100
(alias) function Content(props: MDXProps): Element
import ContentAn function component which renders the MDX content using JSX.
- @param props This value is be available as the named variable
propsinside the MDX component. - @returns A JSX element. The meaning of this may depend on the project configuration. I.e. it could be a ReactPreactor Vuex element.
namespace console
var console: ConsoleThe console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Consoleclass with methods such asconsole.log()console.error()andconsole.warn()that can be used to write to any Node. stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without callingrequire('console').
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemblenor are they consistently asynchronous like all other Node. streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello worldto stdout
console.log('hello %s''world');
// Prints: hello worldto stdout
console.error(new Error('Whoopssomething bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoopssomething bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to stderr
Example using the Console class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(outerr);
myConsole.log('hello world');
// Prints: hello worldto out
myConsole.log('hello %s''world');
// Prints: hello worldto out
myConsole.error(new Error('Whoopssomething bad happened'));
// Prints: [Error: Whoopssomething bad happened]to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to err
- @see source
(method) Console.log(message?: any...optionalParams: any[]): voidPrints to stdout with newline. Multiple arguments can be passedwith the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).
const count = 5;
console.log('count: %d'count);
// Prints: count: 5to stdout
console.log('count:'count);
// Prints: count: 5to stdout
See util.format() for more information.
- @since v0.1.100
(alias) function Thing(): JSX.Element
import Thingfunction Thing(): JSX.Element(alias) function AnotherName(): JSX.Element
import AnotherNamenamespace console
var console: ConsoleThe console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Consoleclass with methods such asconsole.log()console.error()andconsole.warn()that can be used to write to any Node. stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without callingrequire('console').
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemblenor are they consistently asynchronous like all other Node. streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello worldto stdout
console.log('hello %s''world');
// Prints: hello worldto stdout
console.error(new Error('Whoopssomething bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoopssomething bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to stderr
Example using the Console class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(outerr);
myConsole.log('hello world');
// Prints: hello worldto out
myConsole.log('hello %s''world');
// Prints: hello worldto out
myConsole.error(new Error('Whoopssomething bad happened'));
// Prints: [Error: Whoopssomething bad happened]to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to err
- @see source
(method) Console.log(message?: any...optionalParams: any[]): voidPrints to stdout with newline. Multiple arguments can be passedwith the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).
const count = 5;
console.log('count: %d'count);
// Prints: count: 5to stdout
console.log('count:'count);
// Prints: count: 5to stdout
See util.format() for more information.
- @since v0.1.100
(alias) function AnotherName(): JSX.Element
import AnotherNameProps
In § What is MDXwe showed that JavaScript expressionsinside curly bracescan be used in MDX:
import {year} from './data.'
export const name = 'world'
# Hello {name.toUpperCase()}
The current year is {year}
Instead of importing or defining data within MDXdata can also be passed to MDXContent. The passed data is called props. Take for example:
# Hello {props.name.toUpperCase()}
The current year is {props.year}
This file could be used as:
import React from 'react'
import Example from './example.mdx' // Assumes an integration is used to compile MDX -> JS.
// Use a `createElement` call:
console.log(React.createElement(Example{name: 'Venus'year: 2021}))
// Use JSX:
console.log(<Example name="Mars" year={2022} />)
(alias) namespace React
import React(alias) function Example(props: MDXProps): Element
import ExampleAn function component which renders the MDX content using JSX.
- @param props This value is be available as the named variable
propsinside the MDX component. - @returns A JSX element. The meaning of this may depend on the project configuration. I.e. it could be a ReactPreactor Vuex element.
namespace console
var console: ConsoleThe console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Consoleclass with methods such asconsole.log()console.error()andconsole.warn()that can be used to write to any Node. stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without callingrequire('console').
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemblenor are they consistently asynchronous like all other Node. streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello worldto stdout
console.log('hello %s''world');
// Prints: hello worldto stdout
console.error(new Error('Whoopssomething bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoopssomething bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to stderr
Example using the Console class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(outerr);
myConsole.log('hello world');
// Prints: hello worldto out
myConsole.log('hello %s''world');
// Prints: hello worldto out
myConsole.error(new Error('Whoopssomething bad happened'));
// Prints: [Error: Whoopssomething bad happened]to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to err
- @see source
(method) Console.log(message?: any...optionalParams: any[]): void (+1 overload)Prints to stdout with newline. Multiple arguments can be passedwith the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).
const count = 5;
console.log('count: %d'count);
// Prints: count: 5to stdout
console.log('count:'count);
// Prints: count: 5to stdout
See util.format() for more information.
- @since v0.1.100
(alias) namespace React
import Reactfunction React.createElement<MDXProps>(type: React.FunctionComponent<MDXProps>props?: (React.Attributes & MDXProps) | null | undefined...children: React.ReactNode[]): React.FunctionComponentElement<...> (+6 overloads)(alias) function Example(props: MDXProps): Element
import ExampleAn function component which renders the MDX content using JSX.
- @param props This value is be available as the named variable
propsinside the MDX component. - @returns A JSX element. The meaning of this may depend on the project configuration. I.e. it could be a ReactPreactor Vuex element.
(property) name: string(property) year: numbernamespace console
var console: ConsoleThe console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Consoleclass with methods such asconsole.log()console.error()andconsole.warn()that can be used to write to any Node. stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without callingrequire('console').
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemblenor are they consistently asynchronous like all other Node. streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello worldto stdout
console.log('hello %s''world');
// Prints: hello worldto stdout
console.error(new Error('Whoopssomething bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoopssomething bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to stderr
Example using the Console class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(outerr);
myConsole.log('hello world');
// Prints: hello worldto out
myConsole.log('hello %s''world');
// Prints: hello worldto out
myConsole.error(new Error('Whoopssomething bad happened'));
// Prints: [Error: Whoopssomething bad happened]to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to err
- @see source
(method) Console.log(message?: any...optionalParams: any[]): void (+1 overload)Prints to stdout with newline. Multiple arguments can be passedwith the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).
const count = 5;
console.log('count: %d'count);
// Prints: count: 5to stdout
console.log('count:'count);
// Prints: count: 5to stdout
See util.format() for more information.
- @since v0.1.100
(alias) function Example(props: MDXProps): Element
import ExampleAn function component which renders the MDX content using JSX.
- @param props This value is be available as the named variable
propsinside the MDX component. - @returns A JSX element. The meaning of this may depend on the project configuration. I.e. it could be a ReactPreactor Vuex element.
(property) name: string(property) year: numberNote: Users of the MDX VS Code extension can add type checking of props with a JSDoc comment. See mdx-/mdx-analyzer for more info.
Components
There is one special prop: components. It takes an object mapping component names to components. Take this example:
# Hello *<Planet />*
It can be imported from JavaScript and passed components like so:
import Example from './example.mdx' // Assumes an integration is used to compile MDX -> JS.
console.log(
<Example
components={{
Planet() {
return <span ={{color: 'tomato'}}>Pluto</span>
}
}}
/>
)
(alias) function Example(props: MDXProps): Element
import ExampleAn function component which renders the MDX content using JSX.
- @param props This value is be available as the named variable
propsinside the MDX component. - @returns A JSX element. The meaning of this may depend on the project configuration. I.e. it could be a ReactPreactor Vuex element.
namespace console
var console: ConsoleThe console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Consoleclass with methods such asconsole.log()console.error()andconsole.warn()that can be used to write to any Node. stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without callingrequire('console').
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemblenor are they consistently asynchronous like all other Node. streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello worldto stdout
console.log('hello %s''world');
// Prints: hello worldto stdout
console.error(new Error('Whoopssomething bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoopssomething bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to stderr
Example using the Console class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(outerr);
myConsole.log('hello world');
// Prints: hello worldto out
myConsole.log('hello %s''world');
// Prints: hello worldto out
myConsole.error(new Error('Whoopssomething bad happened'));
// Prints: [Error: Whoopssomething bad happened]to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to err
- @see source
(method) Console.log(message?: any...optionalParams: any[]): void (+1 overload)Prints to stdout with newline. Multiple arguments can be passedwith the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).
const count = 5;
console.log('count: %d'count);
// Prints: count: 5to stdout
console.log('count:'count);
// Prints: count: 5to stdout
See util.format() for more information.
- @since v0.1.100
(alias) function Example(props: MDXProps): Element
import ExampleAn function component which renders the MDX content using JSX.
- @param props This value is be available as the named variable
propsinside the MDX component. - @returns A JSX element. The meaning of this may depend on the project configuration. I.e. it could be a ReactPreactor Vuex element.
(property) MDXProps.components?: MDXComponentsThis prop may be used to customize how certain components are rendered.
(method) Planet(): JSX.Element(property) JSX.IntrinsicElements.span: React.DetailedHTMLProps<React.HTMLAttributes<HTMLSpanElement>HTMLSpanElement>(property) React.HTMLAttributes<HTMLSpanElement>.?: React.CSSProperties | undefined(property) StandardLonghandProperties<string | numberstring & {}>.color?: Property.Color | undefinedThe color CSS property sets the foreground color value of an element's text and text decorationsand sets the currentcolor value. currentcolor may be used as an indirect value on other properties and is the default for other color propertiessuch as border-color.
Syntax: <color>
Initial value: canvastext
| Chrome | Firefox | Safari | Edge | IE |
|---|---|---|---|---|
| 1 | 1 | 1 | 12 | 3 |
(property) JSX.IntrinsicElements.span: React.DetailedHTMLProps<React.HTMLAttributes<HTMLSpanElement>HTMLSpanElement>You don’t have to pass components. You can also define or import them within MDX:
import {BoxHeading} from 'rebass'
MDX using imported components!
<Box>
<Heading>Here’s a heading</Heading>
</Box>
Because MDX files are componentsthey can also import each other:
import License from './license.md' // Assumes an integration is used to compile markdown -> JS.
import Contributing from './docs/contributing.mdx'
# Hello world
<License />
---
<Contributing />
Here are some other examples of passing components:
console.log(
<Example
components={{
// Map `h1` (`# heading`) to use `h2`s.
h1: 'h2',
// Rewrite `em`s (`*like so*`) to `i` with a goldenrod foreground color.
em(props) {
return <i ={{color: 'goldenrod'}} {...props} />
},
// Pass a layout (using the special `'wrapper'` key).
wrapper({components...rest}) {
return <main {...rest} />
},
// Pass a component.
Planet() {
return 'Neptune'
},
// This nested component can be used as `<theme.text>hi</theme.text>`
theme: {
text(props) {
return <span ={{color: 'grey'}} {...props} />
}
}
}}
/>
)
namespace console
var console: ConsoleThe console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Consoleclass with methods such asconsole.log()console.error()andconsole.warn()that can be used to write to any Node. stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without callingrequire('console').
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemblenor are they consistently asynchronous like all other Node. streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello worldto stdout
console.log('hello %s''world');
// Prints: hello worldto stdout
console.error(new Error('Whoopssomething bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoopssomething bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to stderr
Example using the Console class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(outerr);
myConsole.log('hello world');
// Prints: hello worldto out
myConsole.log('hello %s''world');
// Prints: hello worldto out
myConsole.error(new Error('Whoopssomething bad happened'));
// Prints: [Error: Whoopssomething bad happened]to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to err
- @see source
(method) Console.log(message?: any...optionalParams: any[]): void (+1 overload)Prints to stdout with newline. Multiple arguments can be passedwith the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).
const count = 5;
console.log('count: %d'count);
// Prints: count: 5to stdout
console.log('count:'count);
// Prints: count: 5to stdout
See util.format() for more information.
- @since v0.1.100
(alias) function Example(props: MDXProps): Element
import ExampleAn function component which renders the MDX content using JSX.
- @param props This value is be available as the named variable
propsinside the MDX component. - @returns A JSX element. The meaning of this may depend on the project configuration. I.e. it could be a ReactPreactor Vuex element.
(property) MDXProps.components?: MDXComponentsThis prop may be used to customize how certain components are rendered.
(property) h1?: Component<React.DetailedHTMLProps<React.HTMLAttributes<HTMLHeadingElement>HTMLHeadingElement>>(property) em?: Component<React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>HTMLElement>>(parameter) props: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>HTMLElement>(property) JSX.IntrinsicElements.i: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>HTMLElement>(property) React.HTMLAttributes<HTMLElement>.?: React.CSSProperties | undefined(property) StandardLonghandProperties<string | numberstring & {}>.color?: Property.Color | undefinedThe color CSS property sets the foreground color value of an element's text and text decorationsand sets the currentcolor value. currentcolor may be used as an indirect value on other properties and is the default for other color propertiessuch as border-color.
Syntax: <color>
Initial value: canvastext
| Chrome | Firefox | Safari | Edge | IE |
|---|---|---|---|---|
| 1 | 1 | 1 | 12 | 3 |
(parameter) props: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>HTMLElement>(property) wrapper?: Component<any>If a wrapper component is definedthe MDX content will be wrapped inside of it.
(parameter) components: any(parameter) rest: any(property) JSX.IntrinsicElements.main: React.DetailedHTMLProps<React.HTMLAttributes<HTMLElement>HTMLElement>(parameter) rest: any(method) Planet(): string(property) theme: {
text(props: any): JSX.Element;
}(method) text(props: any): JSX.Element(parameter) props: any(property) JSX.IntrinsicElements.span: React.DetailedHTMLProps<React.HTMLAttributes<HTMLSpanElement>HTMLSpanElement>(property) React.HTMLAttributes<T>.?: React.CSSProperties | undefined(property) StandardLonghandProperties<string | numberstring & {}>.color?: Property.Color | undefinedThe color CSS property sets the foreground color value of an element's text and text decorationsand sets the currentcolor value. currentcolor may be used as an indirect value on other properties and is the default for other color propertiessuch as border-color.
Syntax: <color>
Initial value: canvastext
| Chrome | Firefox | Safari | Edge | IE |
|---|---|---|---|---|
| 1 | 1 | 1 | 12 | 3 |
(parameter) props: anyThe following keys can be passed in components:
- HTML equivalents for the things you write with markdown such as
h1for# heading(see § Table of components for examples) wrapperwhich defines the layout (but a local layout takes precedence)- anything else that is a valid JSX identifier (
fooQuotecustom-element_$xa1) for the things you write with JSX (like<So />or<like.so />note that locally defined components take precedence)‡
‡ The rules for whether a name in JSX (so x in <x>) is a literal tag name (like h1) or not (like Component) are as follows:
- if there’s a dotit’s a member expression (
<a.b>→h(a.b))which means a reference to the keybtaken from objecta - otherwiseif the name is not a valid JS identifierit’s a literal (
<a-b>→h('a-b')) - otherwiseif it starts with a lowercaseit’s a literal (
<a>→h('a')) - otherwiseit’s a reference (
<A>→h(A))
These keys in components and the difference between literal tag names and references is illustrated as follows. With the following MDX:
* [markdown syntax](#alpha)
* <a href="#bravo">JSX with a lowercase name</a>
* <Link to="#charlie">JSX with a capitalized name</Link>
…passed some components:
import Example from './example.mdx'
console.log(
<Example
components={{
a(props) {
return <a {...props} ={{borderTop: '1px dotted'color: 'violet'}} />
},
Link(props) {
return <a href={props.to} children={props.children} ={{borderTop: '1px dashed'color: 'tomato'}} />
}
}}
/>
)
(alias) function Example(props: MDXProps): Element
import ExampleAn function component which renders the MDX content using JSX.
- @param props This value is be available as the named variable
propsinside the MDX component. - @returns A JSX element. The meaning of this may depend on the project configuration. I.e. it could be a ReactPreactor Vuex element.
namespace console
var console: ConsoleThe console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Consoleclass with methods such asconsole.log()console.error()andconsole.warn()that can be used to write to any Node. stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without callingrequire('console').
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemblenor are they consistently asynchronous like all other Node. streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello worldto stdout
console.log('hello %s''world');
// Prints: hello worldto stdout
console.error(new Error('Whoopssomething bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoopssomething bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to stderr
Example using the Console class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(outerr);
myConsole.log('hello world');
// Prints: hello worldto out
myConsole.log('hello %s''world');
// Prints: hello worldto out
myConsole.error(new Error('Whoopssomething bad happened'));
// Prints: [Error: Whoopssomething bad happened]to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to err
- @see source
(method) Console.log(message?: any...optionalParams: any[]): void (+1 overload)Prints to stdout with newline. Multiple arguments can be passedwith the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).
const count = 5;
console.log('count: %d'count);
// Prints: count: 5to stdout
console.log('count:'count);
// Prints: count: 5to stdout
See util.format() for more information.
- @since v0.1.100
(alias) function Example(props: MDXProps): Element
import ExampleAn function component which renders the MDX content using JSX.
- @param props This value is be available as the named variable
propsinside the MDX component. - @returns A JSX element. The meaning of this may depend on the project configuration. I.e. it could be a ReactPreactor Vuex element.
(property) MDXProps.components?: MDXComponentsThis prop may be used to customize how certain components are rendered.
(property) a?: Component<React.DetailedHTMLProps<React.AnchorHTMLAttributes<HTMLAnchorElement>HTMLAnchorElement>>(parameter) props: React.DetailedHTMLProps<React.AnchorHTMLAttributes<HTMLAnchorElement>HTMLAnchorElement>(property) JSX.IntrinsicElements.a: React.DetailedHTMLProps<React.AnchorHTMLAttributes<HTMLAnchorElement>HTMLAnchorElement>(parameter) props: React.DetailedHTMLProps<React.AnchorHTMLAttributes<HTMLAnchorElement>HTMLAnchorElement>(property) React.HTMLAttributes<HTMLAnchorElement>.?: React.CSSProperties | undefined(property) StandardShorthandProperties<string | numberstring & {}>.borderTop?: Property.BorderTop<string | number> | undefinedThe border-top shorthand CSS property sets all the properties of an element's top border.
Syntax: <line-width> || <line-> || <color>
| Chrome | Firefox | Safari | Edge | IE |
|---|---|---|---|---|
| 1 | 1 | 1 | 12 | 4 |
(property) StandardLonghandProperties<string | numberstring & {}>.color?: Property.Color | undefinedThe color CSS property sets the foreground color value of an element's text and text decorationsand sets the currentcolor value. currentcolor may be used as an indirect value on other properties and is the default for other color propertiessuch as border-color.
Syntax: <color>
Initial value: canvastext
| Chrome | Firefox | Safari | Edge | IE |
|---|---|---|---|---|
| 1 | 1 | 1 | 12 | 3 |
(method) Link(props: any): JSX.Element(parameter) props: any(property) JSX.IntrinsicElements.a: React.DetailedHTMLProps<React.AnchorHTMLAttributes<HTMLAnchorElement>HTMLAnchorElement>(property) React.AnchorHTMLAttributes<HTMLAnchorElement>.href?: string | undefined(parameter) props: anyany(property) React.DOMAttributes<HTMLAnchorElement>.children?: React.ReactNode(parameter) props: anyany(property) React.HTMLAttributes<HTMLAnchorElement>.?: React.CSSProperties | undefined(property) StandardShorthandProperties<string | numberstring & {}>.borderTop?: Property.BorderTop<string | number> | undefinedThe border-top shorthand CSS property sets all the properties of an element's top border.
Syntax: <line-width> || <line-> || <color>
| Chrome | Firefox | Safari | Edge | IE |
|---|---|---|---|---|
| 1 | 1 | 1 | 12 | 4 |
(property) StandardLonghandProperties<string | numberstring & {}>.color?: Property.Color | undefinedThe color CSS property sets the foreground color value of an element's text and text decorationsand sets the currentcolor value. currentcolor may be used as an indirect value on other properties and is the default for other color propertiessuch as border-color.
Syntax: <color>
Initial value: canvastext
| Chrome | Firefox | Safari | Edge | IE |
|---|---|---|---|---|
| 1 | 1 | 1 | 12 | 3 |
…we’d get:
Observe that the first link (#alpha) is dotted and violet. That’s because a is the HTML equivalent for the markdown syntax being used. The second link (#bravo) remains unchangedbecause in JSX syntax a is a literal tag name. The third link (#charlie) is dashed and tomatobecause in JSX syntax Link is a reference.
Layout
There is one special component: the layout. If it is definedit’s used to wrap all content. A layout can be defined from within MDX using a default export:
export default function Layout({children}) {
return <main>{children}</main>;
}
All the things.
The layout can also be imported and then exported with an export … from:
export {Layout as default} from './components.'
The layout can also be passed as components.wrapper (but a local one takes precedence).
MDX provider
You probably don’t need a provider. Passing components is typically fine. Providers often only add extra weight. Take for example this file:
# Hello world
Used like so:
import {createRoot} from 'react-dom/client'
import {Heading/* … */ Table} from './components.'
import Post from './post.mdx' // Assumes an integration is used to compile MDX -> JS.
const components = {
h1: Heading.H1,
// …
table: Table
}
const container = document.getElementById('root')
if (!container) throw new Error('Expected `root`')
const root = createRoot(container)
root.render(<Post components={components} />)
(alias) function createRoot(container: Containeroptions?: RootOptions): Root
import createRootcreateRoot lets you create a root to display React components inside a browser DOM node.
- @see {@link https://react.dev/reference/react-dom/client/createRoot API Reference for
createRoot}
(alias) const Heading: {
H1: React.ComponentType;
}
import Heading(alias) const Table: React.ComponentType<{}>
import Table(alias) function Post(props: MDXProps): Element
import PostAn function component which renders the MDX content using JSX.
- @param props This value is be available as the named variable
propsinside the MDX component. - @returns A JSX element. The meaning of this may depend on the project configuration. I.e. it could be a ReactPreactor Vuex element.
const components: {
h1: React.ComponentType<{}>;
table: React.ComponentType<{}>;
}(property) h1: React.ComponentType<{}>(alias) const Heading: {
H1: React.ComponentType;
}
import Heading(property) H1: React.ComponentType<{}>(property) table: React.ComponentType<{}>(alias) const Table: React.ComponentType<{}>
import Tableconst container: HTMLElement | nullvar document: Document(method) Document.getElementById(elementId: string): HTMLElement | nullReturns a reference to the first object with the specified value of the ID attribute.
- @param elementId String that specifies the ID value.
const container: HTMLElement | nullvar Error: ErrorConstructor
new (message?: stringoptions?: ErrorOptions) => Error (+1 overload)const root: Root(alias) createRoot(container: Containeroptions?: RootOptions): Root
import createRootcreateRoot lets you create a root to display React components inside a browser DOM node.
- @see {@link https://react.dev/reference/react-dom/client/createRoot API Reference for
createRoot}
const container: HTMLElementconst root: Root(method) Root.render(children: React.ReactNode): void(alias) function Post(props: MDXProps): Element
import PostAn function component which renders the MDX content using JSX.
- @param props This value is be available as the named variable
propsinside the MDX component. - @returns A JSX element. The meaning of this may depend on the project configuration. I.e. it could be a ReactPreactor Vuex element.
(property) MDXProps.components?: MDXComponentsThis prop may be used to customize how certain components are rendered.
const components: {
h1: React.ComponentType<{}>;
table: React.ComponentType<{}>;
}That worksthose components are used.
But when you’re nesting MDX files (importing them into each other) it can become cumbersome. Like so:
import License from './license.md' // Assumes an integration is used to compile markdown -> JS.
import Contributing from './docs/contributing.mdx'
# Hello world
<License components={props.components} />
---
<Contributing components={props.components} />
To solve thisa context can be used in ReactPreactand Vue. Context provides a way to pass data through the component tree without having to pass props down manually at every level. Set it up like so:
- Install either
@mdx-/react@mdx-/preactor@mdx-/vuedepending on what framework you’re using - Configure your MDX integration with
providerImportSourceinProcessorOptionsset to that packageso either'@mdx-/react''@mdx-/preact'or'@mdx-/vue' - Import
MDXProviderfrom that package. Use it to wrap your top-most MDX content component and pass it yourcomponentsinstead:
+import {MDXProvider} from '@mdx-/react'
import {createRoot} from 'react-dom/client'
import {Heading/* … */ Table} from './components/index.'
import Post from './post.mdx' // Assumes an integration is used to compile MDX -> JS.
@@ -13,4 +14,8 @@ const components = {
const container = document.getElementById('root')
if (!container) throw new Error('Expected `root`')
const root = createRoot(container)
-root.render(<Post components={components} />)
+root.render(
+ <MDXProvider components={components}>
+ <Post />
+ </MDXProvider>
+)
Now you can remove the explicit and verbose component passing:
import License from './license.md' // Assumes an integration is used to compile markdown -> JS.
import Contributing from './docs/contributing.mdx'
# Hello world
-<License components={props.components} />
+<License />
---
-<Contributing components={props.components} />
+<Contributing />
When MDXProviders are nestedtheir components are merged. Take this example:
console.log(
<MDXProvider components={{h1: Component1h2: Component2}}>
<MDXProvider components={{h2: Component3h3: Component4}}>
<Content />
</MDXProvider>
</MDXProvider>
)
namespace console
var console: ConsoleThe console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Consoleclass with methods such asconsole.log()console.error()andconsole.warn()that can be used to write to any Node. stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without callingrequire('console').
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemblenor are they consistently asynchronous like all other Node. streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello worldto stdout
console.log('hello %s''world');
// Prints: hello worldto stdout
console.error(new Error('Whoopssomething bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoopssomething bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to stderr
Example using the Console class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(outerr);
myConsole.log('hello world');
// Prints: hello worldto out
myConsole.log('hello %s''world');
// Prints: hello worldto out
myConsole.error(new Error('Whoopssomething bad happened'));
// Prints: [Error: Whoopssomething bad happened]to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to err
- @see source
(method) Console.log(message?: any...optionalParams: any[]): void (+1 overload)Prints to stdout with newline. Multiple arguments can be passedwith the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).
const count = 5;
console.log('count: %d'count);
// Prints: count: 5to stdout
console.log('count:'count);
// Prints: count: 5to stdout
See util.format() for more information.
- @since v0.1.100
(alias) function MDXProvider(properties: Readonly<Props>): React.ReactElement
import MDXProviderProvider for MDX context.
- @param properties Properties.
- @returns Element.
- @satisfies {Component}
(property) components?: Readonly<MDXComponents> | MergeComponents | null | undefinedAdditional components to use or a function that creates them (optional).
(property) h1?: Component<React.DetailedHTMLProps<React.HTMLAttributes<HTMLHeadingElement>HTMLHeadingElement>>(alias) const Component1: React.ComponentType<{}>
import Component1(property) h2?: Component<React.DetailedHTMLProps<React.HTMLAttributes<HTMLHeadingElement>HTMLHeadingElement>>(alias) const Component2: React.ComponentType<{}>
import Component2(alias) function MDXProvider(properties: Readonly<Props>): React.ReactElement
import MDXProviderProvider for MDX context.
- @param properties Properties.
- @returns Element.
- @satisfies {Component}
(property) components?: Readonly<MDXComponents> | MergeComponents | null | undefinedAdditional components to use or a function that creates them (optional).
(property) h2?: Component<React.DetailedHTMLProps<React.HTMLAttributes<HTMLHeadingElement>HTMLHeadingElement>>(alias) const Component3: React.ComponentType<{}>
import Component3(property) h3?: Component<React.DetailedHTMLProps<React.HTMLAttributes<HTMLHeadingElement>HTMLHeadingElement>>(alias) const Component4: React.ComponentType<{}>
import Component4(alias) const Content: MDXContent
import Content(alias) function MDXProvider(properties: Readonly<Props>): React.ReactElement
import MDXProviderProvider for MDX context.
- @param properties Properties.
- @returns Element.
- @satisfies {Component}
(alias) function MDXProvider(properties: Readonly<Props>): React.ReactElement
import MDXProviderProvider for MDX context.
- @param properties Properties.
- @returns Element.
- @satisfies {Component}
…which results in h1s using Component1h2s using Component3and h3s using Component4.
To merge differently or not at allpass a function to components. It’s given the current context components and what it returns will be used instead. In this example the current context components are discarded:
console.log(
<MDXProvider components={{h1: Component1h2: Component2}}>
<MDXProvider
components={
function () {
return {h2: Component3h3: Component4}
}
}
>
<Content />
</MDXProvider>
</MDXProvider>
)
namespace console
var console: ConsoleThe console module provides a simple debugging console that is similar to the JavaScript console mechanism provided by web browsers.
The module exports two specific components:
- A
Consoleclass with methods such asconsole.log()console.error()andconsole.warn()that can be used to write to any Node. stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without callingrequire('console').
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemblenor are they consistently asynchronous like all other Node. streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello worldto stdout
console.log('hello %s''world');
// Prints: hello worldto stdout
console.error(new Error('Whoopssomething bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoopssomething bad happened
// at [eval]:5:15
// at Script.runInThisContext (node:vm:132:18)
// at Object.runInThisContext (node:vm:309:38)
// at node:internal/process/execution:77:19
// at [eval]-wrapper:6:22
// at evalScript (node:internal/process/execution:76:60)
// at node:internal/main/eval_string:23:3
const name = 'Will Robinson';
console.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to stderr
Example using the Console class:
const out = getStreamSomehow();
const err = getStreamSomehow();
const myConsole = new console.Console(outerr);
myConsole.log('hello world');
// Prints: hello worldto out
myConsole.log('hello %s''world');
// Prints: hello worldto out
myConsole.error(new Error('Whoopssomething bad happened'));
// Prints: [Error: Whoopssomething bad happened]to err
const name = 'Will Robinson';
myConsole.warn(`Danger ${name}! Danger!`);
// Prints: Danger Will Robinson! Danger!to err
- @see source
(method) Console.log(message?: any...optionalParams: any[]): void (+1 overload)Prints to stdout with newline. Multiple arguments can be passedwith the first used as the primary message and all additional used as substitution values similar to printf(3) (the arguments are all passed to util.format()).
const count = 5;
console.log('count: %d'count);
// Prints: count: 5to stdout
console.log('count:'count);
// Prints: count: 5to stdout
See util.format() for more information.
- @since v0.1.100
(alias) function MDXProvider(properties: Readonly<Props>): React.ReactElement
import MDXProviderProvider for MDX context.
- @param properties Properties.
- @returns Element.
- @satisfies {Component}
(property) components?: Readonly<MDXComponents> | MergeComponents | null | undefinedAdditional components to use or a function that creates them (optional).
(property) h1?: Component<React.DetailedHTMLProps<React.HTMLAttributes<HTMLHeadingElement>HTMLHeadingElement>>(alias) const Component1: React.ComponentType<{}>
import Component1(property) h2?: Component<React.DetailedHTMLProps<React.HTMLAttributes<HTMLHeadingElement>HTMLHeadingElement>>(alias) const Component2: React.ComponentType<{}>
import Component2(alias) function MDXProvider(properties: Readonly<Props>): React.ReactElement
import MDXProviderProvider for MDX context.
- @param properties Properties.
- @returns Element.
- @satisfies {Component}
(property) components?: Readonly<MDXComponents> | MergeComponents | null | undefinedAdditional components to use or a function that creates them (optional).
(property) h2?: Component<React.DetailedHTMLProps<React.HTMLAttributes<HTMLHeadingElement>HTMLHeadingElement>>(alias) const Component3: React.ComponentType<{}>
import Component3(property) h3?: Component<React.DetailedHTMLProps<React.HTMLAttributes<HTMLHeadingElement>HTMLHeadingElement>>(alias) const Component4: React.ComponentType<{}>
import Component4(alias) const Content: MDXContent
import Content(alias) function MDXProvider(properties: Readonly<Props>): React.ReactElement
import MDXProviderProvider for MDX context.
- @param properties Properties.
- @returns Element.
- @satisfies {Component}
(alias) function MDXProvider(properties: Readonly<Props>): React.ReactElement
import MDXProviderProvider for MDX context.
- @param properties Properties.
- @returns Element.
- @satisfies {Component}
…which results in h2s using Component3 and h3s using Component4. No component is used for h1.
If you’re not nesting MDX filesor not nesting them oftendon’t use providers: pass components explicitly.