数学
¥Math
本指南探讨如何在 MDX 中支持数学 (LaTeX)。 MDX 支持标准 Markdown 语法 (CommonMark)。这意味着默认情况下不支持数学。可以使用 remark 插件启用数学:remark-math,结合 rehype 插件:rehype-katex (KaTeX) 或 rehype-mathjax (MathJax)。与其他 remark 和 rehype 插件一样,它们可以在 分别在 ProcessorOptions 中的 remarkPlugins 和 rehypePlugins 中传递。有关插件的更多信息可在 § 扩展 MDX 中找到
¥This guide explores how to support math (LaTeX) in MDX. MDX supports standard markdown syntax (CommonMark). That means math is not supported by default. Math can be enabled by using a remark plugin: remark-math, combined with a rehype plugin: either rehype-katex (KaTeX) or rehype-mathjax (MathJax). Like other remark and rehype plugins, they can be passed in remarkPlugins and rehypePlugins, respectively, in ProcessorOptions. More info on plugins is available in § Extending MDX
假设我们有一个像这样的 MDX 文件:
¥Say we have an MDX file like this:
# $$\sqrt{a^2 + b^2}$$
上面带有数学的 MDX 可以使用以下模块进行转换:
¥The above MDX with math can be transformed with the following module:
import fs from 'node:fs/promises'
import {compile} from '@mdx-js/mdx'
import rehypeKatex from 'rehype-katex'
import remarkMath from 'remark-math'
console.log(
String(
await compile(await fs.readFile('example.mdx'), {
rehypePlugins: [rehypeKatex],
remarkPlugins: [remarkMath]
})
)
)
(alias) module "node:fs/promises"
import fs(alias) function compile(vfileCompatible: Readonly<Compatible>, compileOptions?: Readonly<CompileOptions> | null | undefined): Promise<VFile>
import compileCompile MDX to JS.
- @param vfileCompatible MDX document to parse.
- @param compileOptions Compile configuration (optional).
- @return Promise to compiled file.
(alias) function rehypeKatex(options?: Readonly<Options> | null | undefined): (tree: Root, file: VFile) => undefined
import rehypeKatexRender elements with a language-math (or math-display, math-inline) class with KaTeX.
- @param options Configuration (optional).
- @returns Transform.
(alias) function remarkMath(options?: Readonly<Options> | null | undefined): undefined
import remarkMathAdd support for math.
- @param options Configuration (optional).
- @returns Nothing.
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
var String: StringConstructor
(value?: any) => stringAllows manipulation and formatting of text strings and determination and location of substrings within strings.
(alias) compile(vfileCompatible: Readonly<Compatible>, compileOptions?: Readonly<CompileOptions> | null | undefined): Promise<VFile>
import compileCompile MDX to JS.
- @param vfileCompatible MDX document to parse.
- @param compileOptions Compile configuration (optional).
- @return Promise to compiled file.
(alias) module "node:fs/promises"
import fsfunction readFile(path: PathLike | fs.FileHandle, options?: ({
encoding?: null | undefined;
flag?: OpenMode | undefined;
} & EventEmitter<T extends EventMap<T> = DefaultEventMap>.Abortable) | null): Promise<Buffer> (+2 overloads)Asynchronously reads the entire contents of a file.
If no encoding is specified (using options.encoding), the data is returned as a Buffer object. Otherwise, the data will be a string.
If options is a string, then it specifies the encoding.
When the path is a directory, the behavior of fsPromises.readFile() is platform-specific. On macOS, Linux, and Windows, the promise will be rejected with an error. On FreeBSD, a representation of the directory's contents will be returned.
An example of reading a package.json file located in the same directory of the running code:
import { readFile } from 'node:fs/promises';
try {
const filePath = new URL('./package.json', import.meta.url);
const contents = await readFile(filePath, { encoding: 'utf8' });
console.log(contents);
} catch (err) {
console.error(err.message);
}
It is possible to abort an ongoing readFile using an AbortSignal. If a request is aborted the promise returned is rejected with an AbortError:
import { readFile } from 'node:fs/promises';
try {
const controller = new AbortController();
const { signal } = controller;
const promise = readFile(fileName, { signal });
// Abort the request before the promise settles.
controller.abort();
await promise;
} catch (err) {
// When a request is aborted - err is an AbortError
console.error(err);
}
Aborting an ongoing request does not abort individual operating system requests but rather the internal buffering fs.readFile performs.
Any specified FileHandle has to support reading.
- @since v10.0.0
- @param path filename or
FileHandle - @return Fulfills with the contents of the file.
(property) rehypePlugins?: PluggableList | null | undefinedList of rehype plugins (optional).
(alias) function rehypeKatex(options?: Readonly<Options> | null | undefined): (tree: Root, file: VFile) => undefined
import rehypeKatexRender elements with a language-math (or math-display, math-inline) class with KaTeX.
- @param options Configuration (optional).
- @returns Transform.
(property) remarkPlugins?: PluggableList | null | undefinedList of remark plugins (optional).
(alias) function remarkMath(options?: Readonly<Options> | null | undefined): undefined
import remarkMathAdd support for math.
- @param options Configuration (optional).
- @returns Nothing.
Expand equivalent JSX
<>
<h1>
<span className="katex">
<span className="katex-mathml">
<math xmlns="http://www.w3.org/1998/Math/MathML">…</math>
</span>
<span className="katex-html" aria-hidden="true">
…
</span>
</span>
</h1>
</>
重要的:如果你选择 rehype-katex,你还应该在页面上的某个位置使用 katex.css 以正确设置数学样式。在撰写本文时,最后一个版本是:
¥Important: if you chose rehype-katex, you should also use katex.css somewhere on the page to style math properly. At the time of writing, the last version is:
<!-- Get the latest one from: https://katex.org/docs/browser -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/katex@0.16.11/dist/katex.min.css" integrity="sha384-nB0miv6/jRmo5UMMR1wu3Gz6NLsoTkbqJghGIsx//Rlm+ZU03BU6SQNC66uf4l5+" crossorigin="anonymous">
要获取样式表的最新链接,请转到 katex docs。
¥To get the latest link to the stylesheet, go to katex docs.
注意:另请参阅 remark-mdx-math-enhanced,你可以使用它来支持数学内部的 JavaScript 表达式(例如访问属性或进行计算)
¥Note: see also remark-mdx-math-enhanced, which you can use to support JavaScript expressions inside of math (such as to access properties or to make calculations)