作者:Titus Wormer
使用 MDX
本文解释了如何在你的项目中使用 MDX 文件。 它展示了如何传递 props 以及如何导入、定义或传递组件。 有关如何将 MDX 集成到你的项目中,请参见§ 快速开始。 要了解 MDX 格式的工作原理,我们建议你先阅读 § 什么是 MDX。
目录
MDX 的工作原理
集成将 MDX 语法编译为 JavaScript。 假设我们有一个 MDX 文档 example.mdx:
export function Thing() {
return <>World</>
}
# Hello <Thing />
它大致被转换为以下 JavaScript。 下面的内容可能有助于形成心智模型:
/* @jsxRuntime automatic */
/* @jsxImportSource 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: DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement>function Thing(): JSX.Element(property) JSX.IntrinsicElements.h1: DetailedHTMLProps<HTMLAttributes<HTMLHeadingElement>, HTMLHeadingElement>一些观察:
- 输出是序列化的 JavaScript,仍需要被求值
- 注入了一个注释来配置 JSX 的处理方式
- 它是一个包含 import/export 的完整文件
- 导出了一个组件(
MDXContent)
实际的输出是:
import {Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs} from 'react/jsx-runtime'
export function Thing() {
return _jsx(_Fragment, {children: 'World'})
}
function _createMdxContent(props) {
const _components = {h1: 'h1', ...props.components}
return _jsxs(_components.h1, {children: ['Hello ', _jsx(Thing, {})]})
}
export default function MDXContent(props = {}) {
const {wrapper: MDXLayout} = props.components || {}
return MDXLayout
? _jsx(MDXLayout, {...props, children: _jsx(_createMdxContent, {...props})})
: _createMdxContent(props)
}
(alias) const Fragment: ExoticComponent<FragmentProps>
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: ExoticComponent<FragmentProps>
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 jsx(type: React.ElementType, props: unknown, key?: React.Key): React.ReactElementCreate a React element.
You should not use this function directly. Use JSX and a transpiler instead.
(alias) function _jsx(type: React.ElementType, props: unknown, key?: React.Key): React.ReactElement
import _jsxCreate a React element.
You should not use this function directly. Use JSX and a transpiler instead.
function jsxs(type: React.ElementType, props: unknown, key?: React.Key): React.ReactElementCreate a React element.
You should not use this function directly. Use JSX and a transpiler instead.
(alias) function _jsxs(type: React.ElementType, props: unknown, key?: React.Key): React.ReactElement
import _jsxsCreate a React element.
You should not use this function directly. Use JSX and a transpiler instead.
function Thing(): ReactElement<unknown, string | JSXElementConstructor<any>>(alias) _jsx(type: React.ElementType, props: unknown, key?: React.Key): React.ReactElement
import _jsxCreate a React element.
You should not use this function directly. Use JSX and a transpiler instead.
(alias) const _Fragment: ExoticComponent<FragmentProps>
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): ReactElement<unknown, string | JSXElementConstructor<any>>(parameter) props: anyconst _components: any(property) h1: string(parameter) props: anyany(alias) _jsxs(type: React.ElementType, props: unknown, key?: React.Key): React.ReactElement
import _jsxsCreate a React element.
You should not use this function directly. Use JSX and a transpiler instead.
const _components: anyany(property) children: (string | ReactElement<unknown, string | JSXElementConstructor<any>>)[](alias) _jsx(type: React.ElementType, props: unknown, key?: React.Key): React.ReactElement
import _jsxCreate a React element.
You should not use this function directly. Use JSX and a transpiler instead.
function Thing(): ReactElement<unknown, string | JSXElementConstructor<any>>function MDXContent(props?: {}): ReactElement<unknown, string | JSXElementConstructor<any>>(parameter) props: {}anyconst MDXLayout: any(parameter) props: {}anyconst MDXLayout: any(alias) _jsx(type: React.ElementType, props: unknown, key?: React.Key): React.ReactElement
import _jsxCreate a React element.
You should not use this function directly. Use JSX and a transpiler instead.
const MDXLayout: any(parameter) props: {}(property) children: ReactElement<unknown, string | JSXElementConstructor<any>>(alias) _jsx(type: React.ElementType, props: unknown, key?: React.Key): React.ReactElement
import _jsxCreate a React element.
You should not use this function directly. Use JSX and a transpiler instead.
function _createMdxContent(props: any): ReactElement<unknown, string | JSXElementConstructor<any>>(parameter) props: {}function _createMdxContent(props: any): ReactElement<unknown, string | JSXElementConstructor<any>>(parameter) props: {}更多观察:
- JSX 被编译为函数调用和 React 的导入†
- 内容组件可以接收
{components: {wrapper: MyLayout}}来 包裹所有内容 - 内容组件可以接收
{components: {h1: MyComponent}}来 为标题使用其他组件
† MDX 不与 React 耦合。 你也可以将它与 Preact、 Vue、Emotion、 Theme UI 等 一起使用。 支持经典和自动 JSX 运行时。
MDX 内容
我们刚刚看到 MDX 文件被编译为组件。 你可以在你选择的框架中像使用任何其他组件一样使用这些组件。 以这个文件为例:
# Hi!
它可以在 React 应用中这样导入和使用:
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: Container, options?: 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 React, Preact, or Vuex element.
const container: HTMLElement | nullvar document: Documentwindow.document returns a reference to the document contained in the window.
(method) Document.getElementById(elementId: string): HTMLElement | nullReturns the first element within node's descendants whose ID is elementId.
const container: HTMLElement | nullvar Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)const root: Root(alias) createRoot(container: Container, options?: 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 React, Preact, or Vuex element.
主要内容作为默认导出导出。 所有其他值也都被导出。 看这个例子:
export function Thing() {
return <>World</>
}
# Hello <Thing />
它可以以下列方式导入:
// 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 well, either 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 syntax, but 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 file, create a file with the same name but postfixed with .d.ts next to the MDX file.
For example, given 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 earlier, which 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.js stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without importing thenode:consolemodule.
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something 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(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something 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 passed, with 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: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to 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 well, either 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 syntax, but 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 file, create a file with the same name but postfixed with .d.ts next to the MDX file.
For example, given 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 earlier, which 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 React, Preact, or Vuex element.
(alias) function Thing(): unknown
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.js stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without importing thenode:consolemodule.
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something 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(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something 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 passed, with 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: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to 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 React, Preact, or 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.js stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without importing thenode:consolemodule.
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something 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(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something 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 passed, with 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: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
See util.format() for more information.
- @since v0.1.100
(alias) function Thing(): unknown
import Thingfunction Thing(): unknown(alias) function AnotherName(): unknown
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.js stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without importing thenode:consolemodule.
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something 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(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something 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 passed, with 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: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
See util.format() for more information.
- @since v0.1.100
(alias) function AnotherName(): unknown
import AnotherNameProps
在§ 什么是 MDX中,我们展示了花括号中的 JavaScript 表达式 可以在 MDX 中使用:
import {year} from './data.js'
export const name = 'world'
# Hello {name.toUpperCase()}
当前年份是 {year}
除了在 MDX 中导入或定义数据外,数据也可以传递给 MDXContent。 传递的数据称为 props。 例如:
# Hello {props.name.toUpperCase()}
当前年份是 {props.year}
这个文件可以这样使用:
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 React, Preact, or 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.js stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without importing thenode:consolemodule.
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something 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(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something 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 passed, with 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: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to stdout
See util.format() for more information.
- @since v0.1.100
(alias) namespace React
import Reactfunction createElement<MDXProps>(type: React.FunctionComponent<MDXProps>, props?: (React.Attributes & MDXProps) | null | undefined, ...children: React.ReactNode[]): React.FunctionComponentElement<MDXProps> (+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 React, Preact, or 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.js stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without importing thenode:consolemodule.
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something 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(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something 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 passed, with 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: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to 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 React, Preact, or Vuex element.
(property) name: string(property) year: number注意: MDX VS Code 扩展的用户可以通过 JSDoc 注释添加 props 的类型检查。 参见 mdx-js/mdx-analyzer 获取更多信息。
组件
有一个特殊的 prop:components。 它接收一个将组件名称映射到组件的对象。 看这个例子:
# Hello *<Planet />*
它可以从 JavaScript 导入并像这样传递组件:
import Example from './example.mdx' // Assumes an integration is used to compile MDX -> JS.
console.log(
<Example
components={{
Planet() {
return <span style={{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 React, Preact, or 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.js stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without importing thenode:consolemodule.
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something 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(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something 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 passed, with 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: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to 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 React, Preact, or 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: DetailedHTMLProps<HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>(property) HTMLAttributes<HTMLSpanElement>.style?: CSSProperties | undefined(property) StandardLonghandProperties<string | number, string & {}>.color?: Property.Color | undefinedThis feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Syntax: <color>
Initial value: canvastext
| Chrome | Firefox | Safari | Edge | IE |
|---|---|---|---|---|
| 1 | 1 | 1 | 12 | 3 |
(property) JSX.IntrinsicElements.span: DetailedHTMLProps<HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>你不必传递组件。 你也可以在 MDX 中定义或导入它们:
import {Box, Heading} from 'rebass'
MDX 使用导入的组件!
<Box>
<Heading>这是一个标题</Heading>
</Box>
因为 MDX 文件就是组件,它们也可以相互导入:
import License from './license.md' // Assumes an integration is used to compile markdown -> JS.
import Contributing from './docs/contributing.mdx'
# Hello world
<License />
---
<Contributing />
这里是一些传递组件的其他示例:
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 style={{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 style={{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.js stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without importing thenode:consolemodule.
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something 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(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something 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 passed, with 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: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to 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 React, Preact, or Vuex element.
(property) MDXProps.components?: MDXComponentsThis prop may be used to customize how certain components are rendered.
(property) h1: string(method) em(props: JSX.IntrinsicElements): JSX.Element(parameter) props: JSX.IntrinsicElements(property) JSX.IntrinsicElements.i: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>(property) HTMLAttributes<HTMLElement>.style?: CSSProperties | undefined(property) StandardLonghandProperties<string | number, string & {}>.color?: Property.Color | undefinedThis feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Syntax: <color>
Initial value: canvastext
| Chrome | Firefox | Safari | Edge | IE |
|---|---|---|---|---|
| 1 | 1 | 1 | 12 | 3 |
(parameter) props: JSX.IntrinsicElements(property) wrapper?: Component<any>If a wrapper component is defined, the MDX content will be wrapped inside of it.
(parameter) components: any(parameter) rest: any(property) JSX.IntrinsicElements.main: DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>(parameter) rest: any(method) Planet(): stringType '{ text(props: any): Element; }' is not assignable to type '(NestedMDXComponents | Component<any>) & (Component<JSX.IntrinsicElements> | undefined)'.
Type '{ text(props: any): Element; }' is not assignable to type 'NestedMDXComponents & (new (props: JSX.IntrinsicElements) => JSX.ElementClass)'.
Type '{ text(props: any): Element; }' is not assignable to type 'new (props: JSX.IntrinsicElements) => JSX.ElementClass'.
Type '{ text(props: any): Element; }' provides no match for the signature 'new (props: JSX.IntrinsicElements): JSX.ElementClass'. (2322)(property) theme: {
text(props: any): JSX.Element;
}(method) text(props: any): JSX.Element(parameter) props: any(property) JSX.IntrinsicElements.span: DetailedHTMLProps<HTMLAttributes<HTMLSpanElement>, HTMLSpanElement>(property) HTMLAttributes<T>.style?: CSSProperties | undefined(property) StandardLonghandProperties<string | number, string & {}>.color?: Property.Color | undefinedThis feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Syntax: <color>
Initial value: canvastext
| Chrome | Firefox | Safari | Edge | IE |
|---|---|---|---|---|
| 1 | 1 | 1 | 12 | 3 |
(parameter) props: any以下键可以在 components 中传递:
- 你用 Markdown 编写的内容的 HTML 等价物,例如
h1对应# heading(参见§ 组件表了解示例) wrapper,定义布局(但本地布局优先)- 任何其他有效的 JSX 标识符(
foo、Quote、custom-element、_、$x、a1),用于你用 JSX 编写的内容(如<So />或<like.so />,注意本地定义的组件优先)‡
‡ JSX 中名称(所以 <x> 中的 x)是字面标签名 (如 h1)还是引用(如 Component)的规则如下:
- 如果有点号, 它是成员表达式(
<a.b>→h(a.b)), 意味着从对象a取键b的引用 - 否则, 如果名称不是有效的 JS 标识符, 它是字面值(
<a-b>→h('a-b')) - 否则, 如果以小写字母开头, 它是字面值(
<a>→h('a')) - 否则, 它是引用(
<A>→h(A))
components 中的这些键以及字面标签名和引用之间的差异 如下图所示。 对于以下 MDX:
* [markdown syntax](#alpha)
* <a href="#bravo">JSX with a lowercase name</a>
* <Link to="#charlie">JSX with a capitalized name</Link>
…传递一些组件:
import Example from './example.mdx'
console.log(
<Example
components={{
a(props) {
return <a {...props} style={{borderTop: '1px dotted', color: 'violet'}} />
},
Link(props) {
return <a href={props.to} children={props.children} style={{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 React, Preact, or 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.js stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without importing thenode:consolemodule.
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something 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(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something 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 passed, with 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: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to 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 React, Preact, or Vuex element.
(property) MDXProps.components?: MDXComponentsThis prop may be used to customize how certain components are rendered.
(method) a(props: JSX.IntrinsicElements): JSX.Element(parameter) props: JSX.IntrinsicElements(property) JSX.IntrinsicElements.a: DetailedHTMLProps<AnchorHTMLAttributes<HTMLAnchorElement>, HTMLAnchorElement>(parameter) props: JSX.IntrinsicElements(property) HTMLAttributes<HTMLAnchorElement>.style?: CSSProperties | undefined(property) StandardShorthandProperties<string | number, string & {}>.borderTop?: Property.BorderTop<string | number> | undefinedThis feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Syntax: <line-width> || <line-style> || <color>
| Chrome | Firefox | Safari | Edge | IE |
|---|---|---|---|---|
| 1 | 1 | 1 | 12 | 4 |
(property) StandardLonghandProperties<string | number, string & {}>.color?: Property.Color | undefinedThis feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Syntax: <color>
Initial value: canvastext
| Chrome | Firefox | Safari | Edge | IE |
|---|---|---|---|---|
| 1 | 1 | 1 | 12 | 3 |
(method) Link(props: JSX.IntrinsicElements): JSX.Element(parameter) props: JSX.IntrinsicElements(property) JSX.IntrinsicElements.a: DetailedHTMLProps<AnchorHTMLAttributes<HTMLAnchorElement>, HTMLAnchorElement>(property) AnchorHTMLAttributes<HTMLAnchorElement>.href?: string | undefined(parameter) props: JSX.IntrinsicElementsany(property) DOMAttributes<HTMLAnchorElement>.children?: ReactNode(parameter) props: JSX.IntrinsicElementsany(property) HTMLAttributes<HTMLAnchorElement>.style?: CSSProperties | undefined(property) StandardShorthandProperties<string | number, string & {}>.borderTop?: Property.BorderTop<string | number> | undefinedThis feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Syntax: <line-width> || <line-style> || <color>
| Chrome | Firefox | Safari | Edge | IE |
|---|---|---|---|---|
| 1 | 1 | 1 | 12 | 4 |
(property) StandardLonghandProperties<string | number, string & {}>.color?: Property.Color | undefinedThis feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Syntax: <color>
Initial value: canvastext
| Chrome | Firefox | Safari | Edge | IE |
|---|---|---|---|---|
| 1 | 1 | 1 | 12 | 3 |
…我们会得到:
注意第一个链接(#alpha)是点线和紫色的。 那是因为 a 是所使用的 Markdown 语法的 HTML 等价物。 第二个链接(#bravo)保持不变, 因为在 JSX 语法中 a 是字面标签名。 第三个链接(#charlie)是虚线和番茄色的, 因为在 JSX 语法中 Link 是一个引用。
布局
有一个特殊的组件:布局。 如果定义了,它用于包裹所有内容。 可以在 MDX 中使用默认导出来定义布局:
export default function Layout({children}) {
return <main>{children}</main>;
}
所有内容。
布局也可以导入然后用 export … from 导出:
export {Layout as default} from './components.js'
布局也可以作为 components.wrapper 传递(但本地布局优先)。
MDX provider
你可能不需要 provider。 传递组件通常就够了。 Provider 通常只增加额外的负担。 以这个文件为例:
# Hello world
像这样使用:
import {createRoot} from 'react-dom/client'
import {Heading, /* … */ Table} from './components.js'
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: Container, options?: 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: 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 React, Preact, or Vuex element.
const components: {
h1: ComponentType<{}>;
table: ComponentType<{}>;
}(property) h1: ComponentType<{}>(alias) const Heading: {
H1: React.ComponentType;
}
import Heading(property) H1: ComponentType<{}>(property) table: ComponentType<{}>(alias) const Table: ComponentType<{}>
import Tableconst container: HTMLElement | nullvar document: Documentwindow.document returns a reference to the document contained in the window.
(method) Document.getElementById(elementId: string): HTMLElement | nullReturns the first element within node's descendants whose ID is elementId.
const container: HTMLElement | nullvar Error: ErrorConstructor
new (message?: string, options?: ErrorOptions) => Error (+1 overload)const root: Root(alias) createRoot(container: Container, options?: 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 React, Preact, or Vuex element.
(property) MDXProps.components?: MDXComponentsThis prop may be used to customize how certain components are rendered.
const components: {
h1: ComponentType<{}>;
table: ComponentType<{}>;
}这能工作,那些组件被使用了。
但当你嵌套 MDX 文件(将它们互相导入)时,它会变得 繁琐。 像这样:
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} />
为了解决这个问题,可以在 React、Preact 和 Vue 中使用*上下文*。 上下文提供了一种通过组件树传递数据的方式,而无需 在每一层手动传递 props。 这样设置:
- 安装
@mdx-js/react、@mdx-js/preact或@mdx-js/vue, 取决于你使用的框架 - 配置你的 MDX 集成,将
ProcessorOptions中的providerImportSource设置为该包,即'@mdx-js/react'、'@mdx-js/preact'或'@mdx-js/vue' - 从该包导入
MDXProvider。 用它包裹你最顶层的 MDX 内容组件,并传递你的components:
+import {MDXProvider} from '@mdx-js/react'
import {createRoot} from 'react-dom/client'
import {Heading, /* … */ Table} from './components/index.js'
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>
+)
现在你可以移除显式和冗长的组件传递:
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 />
当 MDXProvider 嵌套时,它们的组件会被合并。 看这个例子:
console.log(
<MDXProvider components={{h1: Component1, h2: Component2}}>
<MDXProvider components={{h2: Component3, h3: 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.js stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without importing thenode:consolemodule.
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something 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(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something 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 passed, with 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: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to 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: React.ComponentType<{}>(alias) const Component1: React.ComponentType<{}>
import Component1(property) h2: React.ComponentType<{}>(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: React.ComponentType<{}>(alias) const Component3: React.ComponentType<{}>
import Component3(property) h3: React.ComponentType<{}>(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}
…结果是 h1 使用 Component1,h2 使用 Component3,h3 使用 Component4。
要以不同方式合并或完全不合并,向 components 传递一个函数。 它会接收当前上下文的 components,它返回的值将被使用。 在这个例子中,当前上下文的组件被丢弃:
console.log(
<MDXProvider components={{h1: Component1, h2: Component2}}>
<MDXProvider
components={
function () {
return {h2: Component3, h3: 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.js stream. - A global
consoleinstance configured to write toprocess.stdoutandprocess.stderr. The globalconsolecan be used without importing thenode:consolemodule.
Warning: The global console object's methods are neither consistently synchronous like the browser APIs they resemble, nor are they consistently asynchronous like all other Node.js streams. See the note on process I/O for more information.
Example using the global console:
console.log('hello world');
// Prints: hello world, to stdout
console.log('hello %s', 'world');
// Prints: hello world, to stdout
console.error(new Error('Whoops, something bad happened'));
// Prints error message and stack trace to stderr:
// Error: Whoops, something 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(out, err);
myConsole.log('hello world');
// Prints: hello world, to out
myConsole.log('hello %s', 'world');
// Prints: hello world, to out
myConsole.error(new Error('Whoops, something bad happened'));
// Prints: [Error: Whoops, something 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 passed, with 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: 5, to stdout
console.log('count:', count);
// Prints: count: 5, to 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: React.ComponentType<{}>(alias) const Component1: React.ComponentType<{}>
import Component1(property) h2: React.ComponentType<{}>(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: React.ComponentType<{}>(alias) const Component3: React.ComponentType<{}>
import Component3(property) h3: React.ComponentType<{}>(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}
…结果是 h2 使用 Component3,h3 使用 Component4。 没有为 h1 使用任何组件。
如果你不嵌套 MDX 文件,或很少嵌套,不要使用 provider:显式传递组件。